鑑於我有以下代碼:我如何構建一個紅寶石從這種情況下哈希?
ENDPOINT = 'http://api.eventful.com'
API_KEY = 'PbFVZfjTXJQWrnJp'
def get_xml(url, options={})
compiled_url = "#{ENDPOINT}/rest#{url}" << "?app_key=#{API_KEY}&sort_order=popularity"
options.each { |k, v| compiled_url << "&#{k.to_s}=#{v.to_s}" }
REXML::Document.new((Net::HTTP.get(URI.parse(URI.escape(compiled_url)))))
end
def event_search(location, date)
get_xml('/events/search',
:location => "#{location}, United Kingdom",
:date => date
)
end
我們訪問由REXML::Document
此格式的XML數據:
events = event_search('London', 'Today').elements
我們可以訪問這些內容是這樣的(這個打印所有標題中事件):
events.each('search/events/event/title') do |title|
puts title.text
end
我正在使用的XML可以是found here。謹以此構建一個哈希像這樣:
{"Title1" => {:title => 'Title1', :date => 'Date1', :post_code => 'PostCode1'},
"Title2" => {:title => 'Title2', :date => 'Date2', :post_code => 'PostCode2'}}
當使用events.each('search/events/event/title')
,events.each('search/events/event/date')
和events.each('search/events/event/post_code')
。
所以我想從上面提供的URL提供的XML中創建一個Hash。謝謝!
使用'nokogiri'..Its爲這個完美的.. –
我不知道該怎麼[做到這一點(http://stackoverflow.com/questions/18077206/how-do- i-loop-through-items-in-xml-in-nokogiri-in-ruby)在Nokogiri。 – raf