JP.
JP.

Reputation: 5594

Mapping XML to Ruby objects

I want to communicate between ruby and other applications in XML. I have defined a schema for this communication and I'm looking for the best way to do the transformation from data in Ruby to the XML and vice versa.

I have an XML document my_document.xml:

<myDocument>
  <number>1</number>
  <distance units="km">20</distance>
</myDocument>

Which conforms to an Schema my_document_type.xsd (I shalln't bother writing it out here).

Now I'd like to have the following class automatically generated from the XSD - is this reasonable or feasible?

# Represents a document created in the form of my_document_type.xsd
class MyDocument
  attr_accessor :number, :distance, :distance_units

  # Allows me to create this object from data in Ruby
  def initialize(data)
    @number = data['number']
    @distance = data['distance']
    @distance_units = data['distance_units']
  end

  # Takes an XML document of the correct form my_document.xml and populates internal systems
  def self.from_xml(xml)
    # Reads the XML and populates:
    doc = ALibrary.load(xml)

    @number = doc.xpath('/number').text()
    @distance = doc.xpath('/distance').text()
    @distance_units = doc.xpath('/distance').attr('units') # Or whatever
  end

  def to_xml
    # Jiggery pokery
  end
end

So that now I can do:

require 'awesomelibrary'

awesome_class = AwesomeLibrary.load_from_xsd('my_document_type.xsd')

doc = awesome_class.from_xml('my_document.xml')

p doc.distance # => 20
p doc.distance_units # => 'km'

And I can also do

doc = awesome_class.new('number' => 10, 'distance_units' => 'inches', 'distance' => '5')

p doc.to_xml

And get:

<myDocument>
  <number>10</number>
  <distance units="inches">5</distance>
</myDocument>

This sounds like fairly intense functionality to me, so I'm not expecting a full answer, but any tips as to libraries which already do this (I've tried using RXSD, but I can't figure out how to get it to do this) or any feasibility thoughts and so on.

Thanks in advance!

Upvotes: 0

Views: 922

Answers (1)

wersimmon
wersimmon

Reputation: 2869

Have you tried Nokogiri? The Slop decorator implements method_missing into the document in such a way that it essentially duplicates the functionality you're looking for.

Upvotes: 1

Related Questions