netghost
2/24/2006 5:16:00 PM
I've actually found that you don't usually want to use the xml
directly. Most of the time, data I get in xml was formed by a
commitee, and they didn't have anyone who was familiar with either XSDs
or structuring information in xml well.
Roughly, I have a base class that has this method in it:
def self::xml_attr(name, path, type, options={})
class_eval do
define_method(name) do
# Get node or attribute
node = REXML::XPath.first(@root, path)
#Convert to a typed value
value = self.class.parse_node(node, type, options) if
node
end
end
once(name) unless options[:cache] == false
end
parse_node manages known types of nodes that I define elsewhere like
strings, floats, dates, arrays, and classes. Like I said, that's
roughly what I use because that's a little old, but this way you can
build model objects similar to ActiveRecord or Og, and map them to the
appropriate xml bits with XPath. I've found that it's pretty flexible
and only comes in around 70 lines of code ;)
Someone posted a nearly identical solution on RubyGarden, but I can't
remember where now. I can pull it up if you're interested.
.adam