From: "Simon Kröger" Date: 2006-03-14T06:16:01+09:00 Subject: Re: Wrapping XML document in Class Hi Miles, interesting idea, i did a quick (proof of concept) hack: ------------------------------------------------------------- class Xmltree attr_accessor :childs attr_accessor :content attr_accessor :attributes def initialize self.childs = [] self.attributes = {}; end def method_missing meth, *args, &block return attributes[args[0]] = args[1] if meth == :[]= return attributes[args[0]] if meth == :[] return self.content = args if meth == '='.intern unless child = childs.assoc(meth.to_s.chomp('=')) childs << child = [meth.to_s.chomp('='), Xmltree.new] end return child[1] if meth.to_s[-1] != ?= child[1].content = args end def to_s childs.map do |t, c| """<#{t} #{c.attributes.map do |a, v| "#{a}=\"#{v}\"" end.join(' ')}>\n#{c}\n""" end.join + content.to_s + (content ? "\n" : '') end end ------------------------------------------------------------- usage: ------------------------------------------------------------- xml = Xmltree.new xml.header.title = 'this is a demo' xml.body.component['type'] = 'the answer' xml.body.component = 42 puts xml ------------------------------------------------------------- output: -------------------------------------------------------------
this is a demo
42 ------------------------------------------------------------- cheers Simon Miles Monroe: > I would like to use Ruby and REXML to wrap an XML document and allow > access to the element nodes, attributes, and text. Essentially I need > an XML document builder loosely coupled from the document. > > It seems like Ruby is powerful enough to code generate a class given an > XML document or build an object at run-time with the appropriate > accessors. > > For instance: > > order = XmlBuilder.new > > order.add("root").add("header") > order.root.add("body") > > order.body.add("component").attributes["type"] = "metric" > > order.write($stdout) > > I'd also like to be able to plug-in input validation when assigning > values to elements and attributes. > > Has anyone done this before? > > Thanks. >