【问题标题】:XML import to PostgreSQL using Nokogiri使用 Nokogiri 将 XML 导入 PostgreSQL
【发布时间】:2015-11-29 04:35:26
【问题描述】:

我想使用 Nokogiri 从 URL 导入 XML 文件并将其保存到我的 PostgreSQL 数据库中。

在我的 schema.rb 中,我有下表:

create_table "centres", force: :cascade do |t|
  t.string   "name"
  t.string   "c_type"
  t.text     "description"
  t.float    "lat"
  t.float    "long"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
end

以下是我正在导入的文件的示例:

<facility>
<id>CG432</id>
<facility_name>Cairncry Community Centre</facility_name>
<expiration>2099-12-31T23:59:59Z</expiration>
<type>Community Centre</type>
<brief_description/>
<lat>57.1601027</lat>
<long>-2.1441739</long>
</facility>

我在 lib/tasks 中创建了以下 import.rake 任务:

require 'rake' 
require 'open-uri'
require 'Nokogiri'

namespace :db do 
    task :xml_parser => :environment do 
        doc = Nokogiri::XML(open("http://sample.xml")) 
        doc.css('centre').each do |node| 
                facility_name = node.xpath("centre").text,
                type = node.xpath("centre").text,
                brief_description = node.xpath("centre").text,
                lat = node.xpath("centre").text,
                long = node.xpath("centre").text,               

                Centre.create(:facility_name => name, :type => c_type, :brief_description => description, :lat => lat, :long => long)
            end
        end
    end

我试过rake db:migraterake -T | grep import

【问题讨论】:

    标签: ruby-on-rails ruby xml import nokogiri


    【解决方案1】:

    您的 XML 不包含 &lt;centre&gt; 元素。如果您只打算使用一次,也无需创建一堆变量。

    doc.css('facility').each do |f|
      centre = Centre.create do |c|
        c.facility_name = node.css("facility_name").first.text
        c.type = node.css("type").first.text
        c.brief_description = node.css("brief_description").first.text
        c.lat = node.css("lat").first.text
        c.long = node.css("long").first.text
      end
    end
    

    如果选择器与您的属性匹配,则执行此操作的更优雅的方法是:

    KEYS = ["facility_name", "type", "brief_description", "lat", "long"]
    doc.css('facility').each do |f|
      values = KEYS.map { |k| node.css(k).first.text }
      Centre.create(Hash[*KEYS.zip(values).flatten])
    end
    

    有关其工作原理的说明,请参见:http://andywenk.github.io/programming/2014/06/27/ruby-create-a-hash-from-arrays/

    【讨论】:

    • 感谢您的解释和链接!
    • 补充一下,我在原始代码中还有一个错误 - 需要“Nokogiri”。当我尝试推送到 Heroku 并运行迁移时,它总是会中止 rake。经过一番研究,我发现 nokogiri 不应该大写。在我改变它之后它工作得很好。
    猜你喜欢
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多