2007年 11月 26日

libxml-ruby の名前空間の解決について

http://d.hatena.ne.jp/keisukefukuda/20071126/p1

Perl と同じように (つまり libxml そのまま) ではありませんが以下のようにしてできます。

require "rubygems"
require "xml/libxml"

require "tempfile"

f = Tempfile.new("xml")
f << <<EOS
<?xml version="1.0" encoding='utf-8'?>
<service xmlns="http://www.w3.org/2007/app"
         xmlns:atom="http://www.w3.org/2005/Atom">
  <workspace>
    <atom:title>Main Site</atom:title>
    <collection href="http://example.org/blog/main">
      <atom:title>My Blog Entries</atom:title>
      <categories href="http://example.com/cats/forMain.cats" />
    </collection>
  </workspace>
</service>
EOS
f.close

doc = XML::Document.file(f.path)

namespaces =  {
	"app" => "http://www.w3.org/2007/app",
	"atom" => "http://www.w3.org/2005/Atom"
}.to_a

p doc.find('/app:service/app:workspace/app:collection/atom:title', namespaces)
#=> <atom:title>My Blog Entries</atom:title>

namespaces にわたすのが配列なのが微妙にひっかかる。(ドキュメントよむと "prefix:uri" みたいな文字列でもわたせるけど圧倒的なキモさなので使わないとおもう)