ruby学习系列--解析网络XML
网络XML地址:http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=madonna&results=2
内容如下:
解析XML代码:
require 'net/http' #处理超文本传输协议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 # 获取XML数据
doc = REXML::Document.new(xml_data) # 析取XML事件信息
titles,links = [],[]
doc.elements.each('ResultSet/Result/Title') do |ele| #获取Title值
titles << ele.text
end
doc.elements.each('ResultSet/Result/Url') do |ele| #获取Url值
links << ele.text
end
titles.each_with_index do |title, idx|
print "#{title} => #{links[idx]}\n" # 打印信息
end
输出结果:
Madonna => http://www.madonna.com/
Madonna (entertainer) - Wikipedia, the free encyclopedia => http://en.wikipedia.org/wiki/Madonna_(entertainer)