title: Ruby code for quick-and-dirty XML serialization?
body: <p>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? </p>
  
  <p>For instance, given:</p>
  
  <pre><code>&lt;Foo bar="1"&gt;&lt;Bat baz="blah"/&gt;&lt;/Foo&gt;
  </code></pre>
  
  <p>How do I avoid writing endless sequences of:</p>
  
  <pre><code>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...  
  </code></pre>
  
  <p>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...</p>
  
  <hr>
  
  <p>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:</p>
  
  <p>"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."</p>
  
  <hr>
  
  <p>I agree with suggestion that a "builder" class plus XmlSimple seems the right path. XML -> Hash -> ? -> Object model (and Profit!)</p>
  
  <hr>
  
  <p>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</p>