Given the moderately complex XML structure (dozens of elements, hundreds of attributes) without an XSD and the desire to create an object model, what an elegant way to avoid writing template methods from_xml () and to_xml ()?
For example, given:
<Foo bar="1"><Bat baz="blah"/></Foo>
How to avoid recording infinite sequences:
class Foo attr_reader :bar, :bat def from_xml(el) @bar = el.attributes['bar'] @bat = Bat.new() @bat.from_xml(XPath.first(el, "./bat") end etc...
I am not against creating an object structure explicitly; this is serialization, which I'm just sure you can take care of some higher-level programs ...
I am not trying to save a line or two for each class (moving from_xml behavior to an initialization method or class, etc.). I am looking for a "meta" solution that duplicates my mental process:
"I know that each element will become the name of the class. I know that every XML attribute will be the name of the field. I know that the code for the assignment is just @ # {attribute_name} = el. [# {Attribute_name}] and then recursion into subelements. And the opposite is to to_xml. "
I agree with the assumption that the builder plus XmlSimple class seems correct. XML → Hash →? → Object model (and profit!)
Update 2008-09-18: Great suggestions from @Roman, @fatgeekuk and @ScottKoon seem to have broken the problem. I downloaded the HPricot source to find out how it solved the problem; the key methods are explicitly instance_variable_set and class_eval. irb works very encouragingly, now I'm moving on to implementation .... Very excited
ruby xml serialization metaprogramming xml-serialization
Larry obrien
source share