XML 使用 Nokogiri 导入到 PostgreSQL

XML import to PostgreSQL using Nokogiri

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

在我的 schema.rb 我有以下 table:

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:migrate,也尝试了 rake -T | grep import

您的 XML 不包含 <centre> 元素。此外,如果您只打算使用它们一次,则无需创建一堆变量。

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/