In order to illustarte how to use REXML to parse XML data returned by Yahoo! APIs, let us try to extract data returned by a Yahoo! web search:

require 'net/http'
require 'rexml/document'

url = 'http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=madonna&results=2'

xml_data = Net::HTTP.get_response(URI.parse(url)).body

doc = REXML::Document.new(xml_data)
titles = []
links = []
doc.elements.each('ResultSet/Result/Title') do |ele|
   titles << ele.text
end
doc.elements.each('ResultSet/Result/Url') do |ele|
   links << ele.text
end

titles.each_with_index do |title, idx|
   print "#{title} => #{links[idx]}\n"
end

The above code will print out all the titles and links of all results.

Advertisements