tags:

views:

428

answers:

4

I have an XML document with a DTD, and would love to be able to access the XML model, something like this:

title = Thing.Items[0].Title

Is there a way, in Ruby, to generate this kind of object model based on a DTD? Or am I stuck using REXML?

Thanks!

+2  A: 

if you include the active_support gem (comes with rails) it adds the method from_xml to the Hash object. You can then call Hash.from_xml(xml_content) and it'll return a hash that you can use to access the data.

I don't know of an easy way to map an xml to an object, but you could create a wrapper class that delegates the method calls to the underlying hash which holds the data.

John Duff
A: 

You can use the ruby version of xml-simple.

You shouldn't need to install the gem as I believe it's already installed with rails. http://xml-simple.rubyforge.org/

TonyLa
A: 

@TonyLa: Looks like xml-simple is the closest I can get at the moment. Thanks!

Tim Sullivan
A: 

I know this question was asked a while back, but if you want the true Thing.Items[0].Title type format, all you need to do is use OpenStruct.

require 'rubygems'
require 'activesupport' # For xml-simple
require 'ostruct' 

h = Hash.from_xml File.read('some.xml')
o = OpenStruct.new h
o.thing.items[0].title
David Richards