ruby学习系列--解析本地XML
本地XML文件如下:
解析XML代码:
require 'rexml/document'
include REXML
file = File.new("d://yahoodemo.xml")
doc = Document.new(file)
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
# print all events
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)