【问题标题】:Parse then Store XML Data from API in Ruby on Rails在 Ruby on Rails 中解析然后存储来自 API 的 XML 数据
【发布时间】:2011-01-10 16:07:09
【问题描述】:

我知道有很多关于这个主题的条目,但我还没有看到如何存储数据的完整图片。我正在尝试创建一个系统,该系统读取然后解析然后存储有关来自 Yahoo Upcoming API 的事件的信息。

url 返回一个非常简单的 xml,看起来像这样

<event>
<id>489875230</id>
<description>Open Bar</description>
<status>Live</status>
<latitude>29.74</latitude>
<longitude>-95.37</longitude>
</event>

我一直在阅读 REXML 和其他内容,但是如何获取元素的值并将它们存储到我的模型中? 目标是将 XML 中所有所需元素的值打印到文本框中,以便随后编辑数据,然后让用户保存在数据库中……我只是很难弄清楚如何做某事解析后的数据。

任何帮助、链接或建议都会对我有很大帮助。

【问题讨论】:

    标签: ruby-on-rails xml model-view-controller api parsing


    【解决方案1】:

    建立一个具有相同属性的模型,将xml解析为哈希,然后用哈希创建模型?

    class CreateEvent < ActiveRecord::Migration
      def self.up
        create_table :events do |t|
        t.id :id
        t.string :decription
        t.string :status
        t.decimal :latitude
        t.decimal :longitude      #( you'll want to set the precision and scale properly here)
      end
    end
    
    
    data = Hash.from_xml <<EOX
    <event>
    <id>489875230</id>
    <description>Open Bar</description>
    <status>Live</status>
    <latitude>29.74</latitude>
    <longitude>-95.37</longitude>
    </event>
    EOX
    
    Event.create!(hash[:event])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      相关资源
      最近更新 更多