Monday, January 21, 2008

[code] Parse XML in Ruby

Needed to call an xml feed bunch of times for work to prototype some algo. I just love how easy this is in Ruby.
require 'rexml/document'
require 'open-uri'
require 'cgi'
include REXML

def searchOne(searchTerm)
searchURL = 'http://foo.com/?q='+CGI.escape(searchTerm)
searchResult = REXML::Document.new(open(searchURL).read)

searchResult.root.each_element do |level0|
level0.each_element do |level1|
if level1.name == 'IWantThisNodeType'
print level1.text + "\n"
level1.each_element do |level2|
# Do something interesting
end
end
end
end
end

searchOne('foobar')