Parsing an XML Document in Ruby

I am using the REXML library.

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

I want to get the value belonging to baa.

How to encode it?

+7
ruby xml
source share
3 answers

try it

 require 'rexml / document'

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

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

I prefer the Nokogiri and Khkrikot nuggets. You can try them if you want.

+9
source share
 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 instead or instead. See REXML :: ELements .

0
source share

Rishava's decision throws 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 a few 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>
0
source share

All Articles