How do I loop through items in XML in Nokogiri in Ruby? [closed]

回眸只為那壹抹淺笑 提交于 2019-12-11 23:17:25

问题


Given I have XML from this address, how would I loop through the search/events/event events? What I mean is loop through the event items and print their details to the screen? So far I have the following code:

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

get_xml being the method which takes the XML from the link above and selects the events node. How would I loop though the items in that events node?


回答1:


Can you try this

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

Output:

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"

Am i understood your requirement correctly?



来源:https://stackoverflow.com/questions/18077206/how-do-i-loop-through-items-in-xml-in-nokogiri-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!