如何在 Ruby 中的 Nokogiri 中遍历 XML 中的项目? [英] How do I loop through items in XML in Nokogiri in Ruby?
本文介绍了如何在 Ruby 中的 Nokogiri 中遍历 XML 中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于我有来自这个地址的 XML ,我将如何遍历 search/events/event
事件?我的意思是循环遍历 event
项目并将它们的详细信息打印到屏幕上?到目前为止,我有以下代码:
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
是从上面的链接中获取 XML 并选择 events
节点的方法.我将如何遍历 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?
推荐答案
你能试试这个吗
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"
我是否正确理解您的要求?
Am i understood your requirement correctly?
这篇关于如何在 Ruby 中的 Nokogiri 中遍历 XML 中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文