Wednesday, September 14, 2011

Oh XPATH

you are so cool.


require 'rubygems'
gem 'nokogiri'
require 'nokogiri'

xml = <<-EOXML
<doc>
<p>
<name>Pippo</name>
<com>
<type>phone</type>
<value>12345</value>
</com>
<com>
<type>fax</type>
<value>67890</value>
</com>
</p>
</doc>
EOXML

doc = Nokogiri::XML(xml)
ps = doc.xpath('//p')

@p = ps.first
def take field
@p.at_xpath("./com[type[text()='#{field}']]/value").text
end

puts "phone: #{take :phone}"
puts "fax: #{take :fax}"






$ ruby nokogiri-xpath.rb
phone: 12345
fax: 67890