How to get a Nokogiri object graph to get serialized recursively?
I am using ROXML with Nokogiri for XML/Ruby Object Mapping in Rails 3 and having a problem with correctly mapping Ruby object graph to xml.
Assuming the following 3 classes:
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
Let's instantiate them:
a = AnyRequestByRequestData.new
b = Resu开发者_如何转开发ltLevelConstraint.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
Calling xml = a.to_xml returns:
#<Nokogiri::XML::Element:0xb2107e name="anyRequestByRequestData" children=[#<Nokogiri::XML::Element:0xb20eee name="resultLevelConstraint" children=[#<Nokogiri::XML::Text:0xb208fe "#<ResultLevelConstraint:0x226143c>">]>]>
Calling xml.serialize :save_with => 0 returns:
<anyRequestByRequestData><resultLevelConstraint>#<ResultLevelConstraint:0x226143c></resultLevelConstraint></anyRequestByRequestData>
So, what happened here is that object ResultLevelConstraint hasn't been serialized correctly.
Calling b.to_xml.serialize :save_with => 0 returns correctly serialized ResultLevelConstraint object:
<resultLevelConstraint><resultLevelConstraintItems><resultLevelConstraintItem resultLevelConfigurationItem=\"1\"><offset>0</offset><limit>10</limit></resultLevelConstraintItem></resultLevelConstraintItems></resultLevelConstraint>
However, this doesn't satisfy my needs. I have deep object graphs and only want to call to_xml.serialize on the root object (a in this example). So, what happened here is that serialize seems to not have been called recursively.
I think it's a Nokogiri issue because to_xml called on the object seems to return a correct Nokogiri object graph. So Roxml seems to work fine...
It just needs the type in AnyRequestByRequestData's xml_accessor:
xml_accessor :result_level_constraint, :as => ResultLevelConstraint, :from => :resultLevelConstraint
精彩评论