I invented this today and as soon as I did, thought that it must have been done before. It has, of course.

require 'rexml/document'

class REXML::Element
  def method_missing(name)
    return attribute(name.to_s) unless attribute(name.to_s).nil?
    return elements[name.to_s]
  end
end

doc = REXML::Document.new(<<EOF
  <root>
    <a b="c">
      <d>e</d>
      <f g="h"/>
      <i><j k="l"/><m/><n>o</n></i>
    </a>
  </root>
EOF
)

a = doc.root.a

p a.i.n.text
=> "o"

p a.b.value
=> "c"
No comments