如何在Ruby中从这个场景构造一个Hash?

时间:2013-08-06 14:53:36

标签: ruby xml hash rexml

鉴于我有以下代码:

  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。谢谢!

2 个答案:

答案 0 :(得分:1)

使用REXML:Document对象上的root()获取根元素,然后使用each_element(“search / events / event”)迭代“event”节点。然后,您可以使用元素上的不同方法从中提取不同的值:http://ruby-doc.org/stdlib-1.9.3/libdoc/rexml/rdoc/REXML/Element.html

答案 1 :(得分:1)

你应该循环事件本身,而不是标题。像这样的东西

events_by_title = {}
elements.each('search/events/event') do |event|
  title = event.get_elements('title').first.text
  events_by_title[title] = {
    :title => title,
    :date => event.get_elements('start_time').first.text
    :post_code => event.get_elements('postal_code').first.text,
  }
end