Results 1 to 8 of 8
Thread: XML Mapping
Sep 26, 2005, 05:17 #1
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.
#--data.xml <person id="001"> <name>Luke Redpath</name> <job>Web Developer</job> <address> <street>Some Street</street> <city>Birmingham</city> <postcode>BH1 23X</postcode> </address> </person>
require 'xml/mapping' # forward declarations class Person; end; class Address; end; class Person include XML::Mapping numeric_node :id, "@id" text_node :name, "name" text_node :job, "job" object_node :address, "address", :class => Address end class Address include XML::Mapping text_node :street, "street" text_node :city, "city", text_node :postcode, "postcode" end # Example usage: person = Person.load_from_file("data.xml") puts person.name => "Luke Redpath" puts person.address.street => "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.