【问题标题】:Parsexml into ruby objects and saveParsexml 成 ruby​​ 对象并保存
【发布时间】:2012-06-27 20:03:31
【问题描述】:

我在 ruby​​ 中使用快乐映射器进行对象映射,然后解析我从 api 获得的 .xml 文件中的 xml 数据。

我在 api 响应中得到一个 zip 文件并将其解压缩以获取 5-6 个具有相同 xml 数据格式的文件。 每个文件中的数据约为 2-3 mb。

我想将这些数据保存在文件中,记住我应该能够对其执行搜索操作。 我不想使用关系数据库,而是希望将数据保存在文件中。 保存数据的更好方法应该是什么,该方法对于以后对该数据执行的搜索操作足够有效。

require 'json'
require 'happymapper'

file_contents = File.read('/home/GhostRider/x.xml')    



  class Message
    include HappyMapper

    tag 'Message'
    element :color, String, :tag => 'Colour'
    element :bg_color, String, :tag => 'BgColour'

  end


  class Status
    include HappyMapper

    tag 'Status'
    element :text, String, :tag => 'Text'
    element :color, String, :tag => 'Colour'
    element :bg_color, String, :tag => 'BgColour'

    has_one :message, Message

  end

  class Line
    include HappyMapper

    tag 'Line' # if you put class in module you need tag
    element :name, String, :tag => 'Name'
    element :color, String, :tag => 'Colour'
    element :bg_color, String, :tag => 'BgColour'
    element :url, String, :tag => 'Url'

    has_one :status, Status

  end

  class Lines
    include HappyMapper

    tag 'Lines' # if you put class in module you need tag

    has_many :lines, Line
  end


item = Lines.parse(file_contents, :single => true)

item.lines.each do |i|

  puts i.name, i.color, i.url, i.status.text, i.status.message.color
end

我需要保存获得的这些数据。

【问题讨论】:

  • 那么,问题是什么?
  • @SergioTulentsev 检查更新,错过了 :(

标签: ruby xml parsing mongoid


【解决方案1】:

更好的方法是使用 xml 选择器解析 xml,例如 nokogiri 或 xml simple 或来自 rails 的默认 Hash.to_xml(xml 文件)。然后分别定义 ruby​​ 类,这有助于更好地控制类并执行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-31
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    相关资源
    最近更新 更多