如何在Ruby中的Nokogiri中循环使用XML中的项目?

时间:2013-08-06 10:11:01

标签: ruby xml nokogiri

鉴于我有XML from this address,我将如何循环search/events/event事件?我的意思是循环遍历event项并将其详细信息打印到屏幕上?到目前为止,我有以下代码:

get_xml('/events/search', :location => 'London, United Kingdom', :date => 'Today').at('events')

get_xml是从上面的链接获取XML并选择events节点的方法。我如何循环events节点中的项目?

1 个答案:

答案 0 :(得分:2)

你能试试吗

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

# Web search for
url = 'http://api.eventful.com/rest/events/search?app_key=PbFVZfjTXJQWrnJp&location=London&date=Today'

# get the XML data as a string
xml_data = Net::HTTP.get_response(URI.parse(url)).body

# extract event information
doc = REXML::Document.new(xml_data)
doc.elements.each('search/events/event/title') do |ele|
   titles = ele.text
   p titles
end

输出:

C:\Users\vinothini\Desktop>ruby sample_nokogiri.rb
"The Ladykillers"
"The 39 Steps"
"Wotever Sex 6 August"
"Phoenix Fringe"
"The Lion King"
"One Man, Two Guvnors"
"Tutorfair event 6th Aug"
"Thriller - Live"
"The Color Purple"
"Summer School Mid-Term Party"

我理解你的要求吗?