How to navigate a XML object in Ruby -
i have regular xml object created response of web service.
i need specific values specific keys... example:
<tag> <tag2> <tag3> <needthisvalue>3</needthisvalue> <tag4> <needthisvalue2>some text</needthisvalue2> </tag4> </tag3> </tag2> </tag>
how can <needthisvalue>
, <needthisvalue2>
in ruby?
i'm big fan of nokogiri:
xml = <<eot <tag> <tag2> <tag3> <needthisvalue>3</needthisvalue> <tag4> <needthisvalue2>some text</needthisvalue2> </tag4> </tag3> </tag2> </tag> eot
this creates document parsing:
require 'nokogiri' doc = nokogiri::xml(xml)
use at
find first node matching accessor:
doc.at('needthisvalue2').class # => nokogiri::xml::element
or search
find nodes matching accessor nodeset, acts array:
doc.search('needthisvalue2').class # => nokogiri::xml::nodeset doc.search('needthisvalue2')[0].class # => nokogiri::xml::element
this uses css accessor locate first instance of each node:
doc.at('needthisvalue').text # => "3" doc.at('needthisvalue2').text # => "some text"
again nodeset using css:
doc.search('needthisvalue')[0].text # => "3" doc.search('needthisvalue2')[0].text # => "some text"
you can use xpath accessors instead of css if want:
doc.at('//needthisvalue').text # => "3" doc.search('//needthisvalue2').first.text # => "some text"
go through the tutorials jumpstart. it's powerful , quite easy use.
Comments
Post a Comment