2012-06-26 48 views
0

我使用快乐的映射器在ruby中进行对象映射,然后解析我从api获得的.xml文件中的xml数据。Parsexml到红宝石对象和保存

我在api响应中获得一个zip文件,并将其解压缩以获得具有相同xml格式数据的5-6个文件。 每个文件中的数据大约为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 

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

+0

那么,这有什么问题? –

+0

@SergioTulentsev检查更新,错过dat :​​( – Bijendra

+0

定义“足够高效”。 –

回答

1

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