Extracting Data From a Document's Tree Structure
orders_xml = %{
<orders>
<order>
<number>1</number>
<date>02/10/2008</date>
<customer>C</customer>
<items>
<item upc="0" desc="Roses" qty="240" />
<item upc="1" desc="Candy" qty="160" />
</items>
</order>
</orders>}
require 'rexml/document'
orders = REXML::Document.new(orders_xml)
orders.root.each_element do |order| # each <order> in <orders>
order.each_element do |node| # <customer>, <items>, etc. in <order>
if node.has_elements?
node.each_element do |child| # each <item> in <items>
puts "#{child.name}: #{child.attributes['desc']}"
end
else
# the contents of <number>, <date>, etc.
puts "#{node.name}: #{node.text}"
end
end
end
Related examples in the same category