我在Rails 3中使用ROXML和Nokogiri进行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 => 0返回:
<anyRequestByRequestData><resultLevelConstraint>#<ResultLevelConstraint:0x226143c></resultLevelConstraint></anyRequestByRequestData>
所以,这里发生的是对象ResultLevelConstraint没有被正确序列化。
调用 b.to_xml。serialize:save_with => 0返回正确序列化的ResultLevelConstraint对象:
<resultLevelConstraint><resultLevelConstraintItems><resultLevelConstraintItem resultLevelConfigurationItem="1"><offset>0</offset><limit>10</limit></resultLevelConstraintItem></resultLevelConstraintItems></resultLevelConstraint>
然而,这并不能满足我的需要。我有深度对象图,只想调用to_xml。在根对象(本例中为a)上序列化。所以,这里发生的事情是serialize似乎没有被递归调用。
我认为这是一个Nokogiri问题,因为在对象上调用to_xml似乎返回一个正确的Nokogiri对象图。所以Roxml似乎工作得很好…
它只需要AnyRequestByRequestData的xml_accessor中的类型:
xml_accessor :result_level_constraint, :as => ResultLevelConstraint, :from => :resultLevelConstraint