Mittwoch, 16. November 2011

How to use Nokogiri with XML namespace in Ruby

I recently wanted to fetch some data published by the ECB in XML format. Ruby + Nokogiri were very handy doing it. The tricky thing was to include the namespace in the XPath query.
#!/usr/bin/env ruby
require 'pp'
require 'nokogiri'
require 'open-uri'
doc = Nokogiri::XML(open('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'))
cubes = doc.xpath("//ecb:Cube[@currency='CAD']",
'ecb' => 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref')
cubes.each { |c|
print c.attribute('currency'), "=", c.attribute('rate').value.to_f, "\n"
}
view raw gistfile1.txt hosted with ❤ by GitHub