Given a moderately complex XML structure (dozens of elements, hundreds of attributes) with no XSD and a desire to create an object model, what's an elegant way to avoid writing boilerplate from_xml() and to_xml() methods?
For instance, given:
<Foo bar="1"><Bat baz="blah"/></Foo>
How do I avoid writing endless sequences of:
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 don't mind creating the object structure explicitly; it's the serialization that I'm just sure can be taken care of with some higher-level programming...
I am not trying to save a line or two per class (by moving from_xml behavior into initializer or class method, etc.). I am looking for the "meta" solution that duplicates my mental process:
"I know that every element is going to become a class name. I know that every XML attribute is going to be a field name. I know that the code to assign is just @#{attribute_name} = el.[#{attribute_name}] and then recurse into sub-elements. And reverse on to_xml."
I agree with suggestion that a "builder" class plus XmlSimple seems the right path. XML -> Hash -> ? -> Object model (and Profit!)
Update 2008-09-18 AM: Excellent suggestions from @Roman, @fatgeekuk, and @ScottKoon seem to have broken the problem open. I downloaded HPricot source to see how it solved the problem; key methods are clearly instance_variable_set and class_eval . irb work is very encouraging, am now moving towards implementation .... Very excited