0

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?

1
  • Are you sure that is what you want? Do you mean <needThisValue>3</needThisValue> and <needThisValue2>some text</needThisValue2>? Or, do you mean 3 and some text? Commented Jul 1, 2011 at 23:41

4 Answers 4

5

I'm a big fan of Nokogiri:

xml = <<EOT
<tag>
 <tag2>
  <tag3>
   <needThisValue>3</needThisValue>
   <tag4>
    <needThisValue2>some text</needThisValue2>
   </tag4>
  </tag3>
 </tag2>
</tag>
EOT

This creates a document for parsing:

require 'nokogiri'
doc = Nokogiri::XML(xml)

Use at to find the first node matching the accessor:

doc.at('needThisValue2').class # => Nokogiri::XML::Element

Or search to find all nodes matching the accessor as a NodeSet, which acts like an Array:

doc.search('needThisValue2').class # => Nokogiri::XML::NodeSet
doc.search('needThisValue2')[0].class # => Nokogiri::XML::Element

This uses a CSS accessor to locate the first instance of each node:

doc.at('needThisValue').text # => "3"
doc.at('needThisValue2').text # => "some text"

Again with the 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 you want:

doc.at('//needThisValue').text # => "3"
doc.search('//needThisValue2').first.text # => "some text"

Go through the tutorials to get a jumpstart. It's very powerful and quite easy to use.

Sign up to request clarification or add additional context in comments.

Comments

2
require "rexml/document"
include REXML
doc = Document.new string
puts XPath.first(doc, "//tag/tag2/tag3/needThisValue").text
puts XPath.first(doc, "//tag/tag2/tag3/tag4/needThisValue2").text

Comments

0

Try this Nokogiri tutorial. You'll need to install nokogiri gem.

Good luck.

Comments

0

Check out the Nokogiri gem. You can read some tutorials enter link description here. It's fast and simple.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.