freddiefujiwara
freddiefujiwara

Reputation: 59029

Parse XML document in Ruby

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?

Upvotes: 7

Views: 2136

Answers (3)

Robert Klemme
Robert Klemme

Reputation: 2179

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>

Upvotes: 0

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

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.

Upvotes: 9

Simone Carletti
Simone Carletti

Reputation: 176352

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.

Upvotes: 0

Related Questions