Monday 29 April 2013

Using NOKUGIRI gem to parse XML

Nokugiri gem can be used to parse html and xml files. Below is a small tutorial on how to do this in UBUNTU. (Installation procedure for windows is different I gue

1) Add gem "nokogiri" inyour gem file.

2) Run bundle install.

3) To open the xml file use this:-
  doc = Nokogiri::XML(open(filename/URL))

4)Suppose you want to read the content from the folowing xml:-
<first_tag>
<second_tag>Hi XYZ</second_tag>
</first_tag>
To read the content do the following:-
doc.css("first_tag second_tag").map {|node|
                 
        p  tag<<node.children.text
        }

This will output HI XYZ.

5) There are also some other methods which can be used to read the xml like:-

data=doc.xpatch("//first_tag").map do |item|
  [
    item.search("second_tag").first.content
  ]
end

No comments:

Post a Comment