I thought I'd start a small thread to give a bit of publicity to the excellent Ruby XML-Mapping library - I've not seen it mentioned often and its quite low down on the RubyForge listings - a shame, as it is a great way of working with XML.
Ruby has a great XML parser in the form of REXML. However, even with the greatest of XML parsers, XML parsing can be incredibly tedious, especially when you are working with the same XML data/schema on a regular basis. XML-Mapping solves this problem by enabling you to create native Ruby objects that map directly to your XML schema. Kind of like ActiveRecord for XML, thought not quite as "automatic" as ActiveRecord - a bit of config is still needed.
Here is a brief example. XML nodes can be mapped to native Ruby objects, including your own custom objects.
Now, to create our objects, we simply create the class definitions, include the XML-mapping library, and set out our mappings. Going by the example above, I'd say we have two custom objects, Person and Address, and the rest can be mapped to native types (people is an array, everything else is a string).Code:
For more examples and the api:Code:
# forward declarations
class Person; end;
class Address; end;
numeric_node :id, "@id"
text_node :name, "name"
text_node :job, "job"
object_node :address, "address", :class => Address
text_node :street, "street"
text_node :city, "city",
text_node :postcode, "postcode"
# Example usage:
person = Person.load_from_file("data.xml")
=> "Luke Redpath"
=> "Some Street"
It can be installed as a gem:
gem install xml-mapping
Things that could be improved? It would be really cool if it could automatically determine the mappings from an XSD schema file if an XML file had one associated with it. That would make it as awesome as ActiveRecord.