Sunday 16 July 2017

Remove particular XML tag with Nokogiri

Suppose that we have XML -


xml_content = <?xml version="1.0"?>
     <book>
        <author>Gambardella, Matthew</author>
        <title>XML Developer's Guide</title>
        <genre>Computer</genre>
        <price>44.95</price>
        <publish_date>2000-10-01</publish_date>
        <description>An in-depth look at creating applications 
        with XML.</description>
     </book>


And we need to remove <genre> tag but keep the inside that tag -


 <?xml version="1.0"?>
    <book>
       <author>Gambardella, Matthew</author>
       <title>XML Developer's Guide</title>
       Computer
       <price>44.95</price>
       <publish_date>2000-10-01</publish_date>
       <description>An in-depth look at creating applications 
       with XML.</description>
    </book>


We can achieve this with Nokogiri -


 
require 'nokogiri'
doc = Nokogiri::XML 'xml_content'
doc.xpath('//genre').each do |tag|
  tag.replace(Nokogiri::XML::Text.new(tag.text, tag.document))
end
doc.inner_html
 

5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. It is Great POST. its is very very helpful for all of us and I never get bored while reading your POST because, they are
    becomes a more and more interesting from the starting lines until the end.Ruby on Rails Online Course Bangalore.

    ReplyDelete
  3. Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best. ROR Development Company India,

    ReplyDelete
  4. Thank you.Well it was nice post and very helpful information onRuby on Rails Online Training Hyderabad

    ReplyDelete
  5. Thanks for sharing this blog post,Nice written skill selenium Online Training Hyderabad

    ReplyDelete