I have a regular xml object created from a response of a web service.
I need to get some specific values from some specific keys… for example:
<tag>
<tag2>
<tag3>
<needThisValue>3</needThisValue>
<tag4>
<needThisValue2>some text</needThisValue2>
</tag4>
</tag3>
</tag2>
</tag>
How can I get <needThisValue> and <needThisValue2> in Ruby?
I’m a big fan of Nokogiri:
This creates a document for parsing:
Use
atto find the first node matching the accessor:Or
searchto find all nodes matching the accessor as a NodeSet, which acts like an Array:This uses a CSS accessor to locate the first instance of each node:
Again with the NodeSet using CSS:
You can use XPath accessors instead of CSS if you want:
Go through the tutorials to get a jumpstart. It’s very powerful and quite easy to use.