メソッドでアクセスできると、みょーに気持ちいいんだよなぁ…
JavaScriptの影響かしら?
require "rexml/document"class XMLPrototype
def initialize(source)
@root = (source.is_a? REXML::Element) ? source : REXML::Document.new(source).root
enddef [](name)
@root.attribute(name)
enddef method_missing(name, *args, &block)
elements = *__elements__(name)unless elements
REXML::Element.method_defined?(name) ? @root.send(name, *args, &block) : nil
else
elements
end
enddef to_a(name=nil)
name ? __elements__(name) : [self]
enddef to_s
@root.to_s
endprivate
def __elements__(name)
path = name.to_s.gsub("_", ":")
@root.get_elements(path).collect {|element| XMLPrototype.new(element)}
end
end
こんな感じで。
require "open-uri"xml = nil
open("http://b.hatena.ne.jp/hotentry?mode=rss") {|f| xml = XMLPrototype.new(f.read)}xml.channel.items.rdf_Seq.rdf_li.each {|li|
puts li["rdf:resource"].value
}