如何让Nokogiri对象图递归地序列化?

时间:2011-07-13 10:56:20

标签: ruby-on-rails xml ruby-on-rails-3 serialization nokogiri

我在Rails 3中使用带有Nokogiri的ROXML进行XML / Ruby对象映射,并且在将Ruby对象图正确映射到xml时遇到了问题。

假设以下3个类:

class AnyRequestByRequestData
  include ROXML

  xml_name :anyRequestByRequestData
  xml_accessor :request_data
  xml_accessor :result_level_configuration
  xml_accessor :result_level_constraint, :from => :resultLevelConstraint
  xml_accessor :result_format
end

class ResultLevelConstraint
  include ROXML

  xml_name :resultLevelConstraint
  xml_accessor :result_level_constraint_items, :as => [ResultLevelConstraintItem], :in => :resultLevelConstraintItems
end

class ResultLevelConstraintItem
  include ROXML

  xml_name :resultLevelConstraintItem
  xml_accessor :result_level_configuration_item, :from => "@resultLevelConfigurationItem"
  xml_accessor :offset
  xml_accessor :limit
end

让我们实例化它们:

a = AnyRequestByRequestData.new
b = ResultLevelConstraint.new
c = ResultLevelConstraintItem.new
c.result_level_configuration_item = 1
c.offset = 0
c.limit = 10
b.result_level_constraint_items = [c]
a.result_level_constraint = b

调用 xml = a.to_xml 会返回:

#<Nokogiri::XML::Element:0xb2107e name="anyRequestByRequestData" children=[#<Nokogiri::XML::Element:0xb20eee name="resultLevelConstraint" children=[#<Nokogiri::XML::Text:0xb208fe "#<ResultLevelConstraint:0x226143c>">]>]>

调用 xml.serialize:save_with =&gt; 0 返回:

<anyRequestByRequestData><resultLevelConstraint>#&lt;ResultLevelConstraint:0x226143c&gt;</resultLevelConstraint></anyRequestByRequestData>

所以,这里发生的是对象 ResultLevelConstraint 尚未正确序列化。

调用 b.to_xml.serialize:save_with =&gt; 0 返回正确序列化的ResultLevelConstraint对象:

<resultLevelConstraint><resultLevelConstraintItems><resultLevelConstraintItem resultLevelConfigurationItem=\"1\"><offset>0</offset><limit>10</limit></resultLevelConstraintItem></resultLevelConstraintItems></resultLevelConstraint>

然而,这并不能满足我的需要。我有深度对象图,只想在根对象上调用 to_xml.serialize (在本例中为a)。所以,这里发生的事情是序列化似乎没有被递归调用。

我认为这是一个Nokogiri问题,因为在对象上调用的 to_xml 似乎返回了正确的Nokogiri对象图。所以Roxml似乎工作得很好......

1 个答案:

答案 0 :(得分:1)

它只需要AnyRequestByRequestData的xml_accessor中的类型:

xml_accessor :result_level_constraint, :as => ResultLevelConstraint, :from => :resultLevelConstraint