【问题标题】:rake task to parse xml from website into rails databaserake 任务将 xml 从网站解析到 rails 数据库
【发布时间】:2015-10-28 15:13:30
【问题描述】:

我正在尝试将数据从在线 xml 文件导入到我已经构建的 rails 数据库中。以下是我写的整个 rake 任务。它保存在我的应用程序的 lib/tasks/xml_parser.rake 中。

  require 'open-uri'
  doc = Nokogiri::XML(open("https://dl.dropboxusercontent.com/u/21695507/openplaques/gb_20151004.xml")) do |config|
    config.options = Nokogiri::XML::ParseOptions::NOERROR
  end

  doc.css('plaque').each do |node|
    children = node.children

    Plaque.create(
    :title => children.css('title').inner_text,
    :subject => children.css('subjects').inner_text,
    :colour => children.css('colour').inner_text,
    :inscription => children.css('inscription raw').inner_text,
    :latitude => children.css('geo')['latitude'],
    :longitude => children.css('geo')['longitude'],
    :address => children.css('address').inner_text,
    :organisation => children.css('author').inner_text,
    :date_erected => children.css('author').inner_text,
    )
  end 
end 

我正在尝试使用以下命令从命令行运行它: 当我运行该命令时,它返回“killed”。 我的问题是:

(1) 上面的代码有什么明显的错误吗?

(2) 是否需要在 xml_parser.rake 文件或其他地方编写其他代码才能创建 rake 任务?

(3)假设代码完整且正确,为什么返回“killed”?

(4) 是否有一个好的资源可以逐步向我展示如何将 xml 从网站导入到 rails 数据库?

感谢您的宝贵时间。

【问题讨论】:

  • 在执行 rake 任务之前,您可以在控制台中逐行查看它是否有效。
  • :date_erected 行末尾有多余的逗号
  • 谢谢。我删除了多余的逗号。这是 rake 任务的正确语法吗?
  • 表面上看起来不错。如果您使用--trace 运行任务,它应该会在失败时为您提供正确的堆栈跟踪。不过,我仍然建议先在控制台中执行此操作。
  • 我尝试使用 --trace 运行它,它也返回“Killed”。在控制台中逐行运行是什么意思?可以举个例子吗?

标签: ruby-on-rails xml


【解决方案1】:

首先,您可以删除创建括号末尾的多余逗号。如果这不起作用...

试试这个

 require 'rake' 
    require 'open-uri' 
    namespace :xml_parser do 
    task :new_task => :environment do 
    doc = Nokogiri::XML(open("https://dl.dropboxusercontent.com/u/21695507/openplaques/gb_20151004.xml")) 
doc.css('plaque').each do |node| 
children = node.children 
Plaque.create(
            :title => children.css('title').inner_text,
            :subject => children.css('subjects').inner_text,
            :colour => children.css('colour').inner_text,
            :inscription => children.css('inscription raw').inner_text,
            :latitude => children.css('geo')['latitude'],
            :longitude => children.css('geo')['longitude'],
            :address => children.css('address').inner_text,
            :organisation => children.css('author').inner_text,
            :date_erected => children.css('author').inner_text
            )   
    end
    end

然后运行rake xml_parser : new_task 那应该行得通。 (另外,请检查您是否正确导入了:organisation:date_erected 字段)。

【讨论】:

  • 谢谢,这是在终端中运行的。但是,我现在收到一条错误消息:“TypeError:没有将 String 隐式转换为 Integer”。但是,数据库字段的数据类型都是字符串或文本,那么为什么要尝试转换为整数呢?
  • 经纬度字段?可以分享一下 XML 文件吗?
猜你喜欢
  • 2012-07-31
  • 2012-02-12
  • 2012-02-12
  • 1970-01-01
  • 2012-07-23
  • 2014-08-10
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
相关资源
最近更新 更多