7

I'm using REXML library.

<foo>
  <baa>value</baa>
</foo>

I want to get the value that belongs to <baa>.

How can I do it?

1
  • I assume your XML is supposed to be "<foo><baa>value</baa></foo>", i.e. with ending tags. Commented Jul 1, 2009 at 6:11

3 Answers 3

9

try this

require 'rexml/document'

doc = REXML::Document.new File.new('mydoc.xml')

doc.elements('*/foo/baa') { |element| puts element.get_text }

I prefer Nokogiri and Hpricot gems myself. You can try them if you want.

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

Comments

0
require 'rexml/document'

xml = <<-EOS
<foo>
  <baa>value</baa>
</foo>
EOS

doc = REXML::Document.new(xml)
doc.root.elements.each("baa") { |element| p element.text }

If you want to collect values you can use to_a.map or inject instead. See REXML::ELements.

Comments

0

Rishav's solution throws for me.

11:50:18 Temp$ ruby rx.rb
rx.rb:5:in `elements': wrong number of arguments (1 for 0) (ArgumentError)
        from rx.rb:5
11:50:25 Temp$

Here are some alternative approaches:

require 'rexml/document'

doc = REXML::Document.new DATA

doc.elements.each('//foo/baa') { |element| puts element.get_text }
baas = REXML::XPath.each(doc, '//foo/baa/text()') {|txt| p txt}
p baas

__END__
<foo>
  <baa>value</baa>
</foo>

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.