Jumat, 16 Desember 2011

Parsing XML with Nokogiri

There are so many related articles about this things.

But i want to write down the spesific about how to parsing xml on nokogiri,

   require 'open-uri'
   doc = Nokogiri::HTML(open("http://www.w3schools.com/xml/note.xml"))   

This is the result example:

Click it. This is the sample xml:

         The Xml File

and you want to get the "Jani" from the xml.

here what we do

because Jani is children from note node.
so we have to call the note first.

we will get the note's children.:

      result = doc.xpath('//note')            
and last, after we get the children. we parse with :

      result = result.xpath('//from').text           

Or, we could make it simplifier by:

     doc = Nokogiri::HTML(open("http://www.w3schools.com/xml/note.xml")) 
     result = doc.xpath('//note/from').text      
# in this case, we are find for the root of "note", and then search the children node, named "from". and this will be "JANI"

Hope it will helps

0 komentar:

Posting Komentar

Copyright 2009 ruby on rails. Powered by Blogger
Blogger Templates created by Deluxe Templates
Wordpress by Wpthemescreator