tags:

views:

273

answers:

3

I'm using REXML library.

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

I want to get value belongs to baa.

How to code it ?

+3  A: 

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.

Rishav Rastogi
A: 
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.

Simone Carletti
A: 

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>
Robert Klemme