ruby + XPath

To document an annoying example…

1
2
3
4
5
6
require 'rexml/document'
include REXML #namespace convenience
doc = Document.new File.read("chiquita_shipments.xml")
doc.elements.each("//fruits/fruit/color") do |el| 
  puts el.parent if el.texts[0].to_s == "yellow"
end

Let’s say chiquita_shipments.xml looks like…

1
2
3
4
5
6
7
8
9
<pallet number='1'>
<fruits>
  <fruit>
    <name>banana</name>
    <color>yellow</color>
    <round>no</round>
  </fruit>
</fruits>
<pallet>

Leave a Reply

You must be logged in to post a comment.