プログラミング言語とネームスペース(1)

XMLを扱う言語にとってネームスペースはある場合には鬼門にもあたるような存在ではないかと思えます.例えばパーサーを作るのだったら

<?xml version="1.0" encoding="UTF-8"?>
<a xmlns="uri:xslt:testa">
  <b xmlns="uri:xslt:testb">
    <c xmlns="uri:xslt:testc">
      text
    </c>
  </b>
</a>

とデフォルトネームスペースが要素a~cとナビゲートするのに従って変わってゆくのを管理しなければなりません.XMLを読むアプリケーションプログラムでも、読み込むXMLがネームスペース付きの場合、どのようにハンドリングしているかは結構興味があるとこころです.今までのサンプルは一切ネームスペースを使っていませんでした.すこし恣意的ですがサンプルのXMLを次のように変えてみます.

[MusicLibraryNS.xml]
<?xml version="1.0" encoding="utf-8"?>
<musicLibrary xmlns="uri:music:library" xmlns:cd="uri:music:cd" xmlns:ttl="uri:music:title">
  <cd:cd id="1">
    <ttl:title>Parallel Lines</ttl:title>
    <year>2001</year>
    <artist>Blondie</artist>
    <genre>New Wave</genre>
  </cd:cd>
  <cd:cd id="2">
    <ttl:title>Bat Out of Hell</ttl:title>
    <year>2001</year>
    <artist>Meatloaf</artist>
    <genre>Rock</genre>
  </cd:cd>
  <cd:cd id="3">
    <ttl:title>Abbey Road</ttl:title>
    <year>1987</year>
    <artist>The Beatles</artist>
    <genre>Rock</genre>
  </cd:cd>
  <cd:cd id="4">
    <ttl:title>The Dark Side of the Moon</ttl:title>
    <year>1994</year>
    <artist>Pink Floyd</artist>
    <genre>Rock</genre>
  </cd:cd>
  <cd:cd id="5">
    <ttl:title>Thriller</ttl:title>
    <year>2001</year>
    <artist>Michael Jackson</artist>
    <genre>Pop</genre>
  </cd:cd>
</musicLibrary>

従来の発売年が1994年のアルバムタイトルをxsl:messageで表示するスタイルシートは以下のようになります.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
    xmlns:mlp="uri:music:library"
    xmlns:cdp="uri:music:cd"
    xmlns:ttlp="uri:music:title"
    version="2.0">
    <xsl:template match="/">
        <xsl:variable name="title" as="element()?" select="/mlp:musicLibrary/cdp:cd[string(mlp:year) = '1994']/ttlp:title"/>
        <xsl:message select="concat('title=''',string($title),'''')"/>
    </xsl:template>
</xsl:stylesheet>

結果は従来と同じ title='The Dark Side of the Moon' となります.

誰でもたいてい一度は間違えるところですが、入力XMLファイルがデフォルトネームスペースを使用していても、それはネームスペースプリフィックス付きのXPath式で参照しなければなりません.(この場合mlp:musicLibrary)またネームスペースプリフィックスは単なる識別子なので、入力XMLで使用しているネームスペースプリフィックスと同じである必要はありません.(cd⇒cdp、ttl⇒ttlp)

XSLTスタイルシートの場合は、このようにネームスペースをXSLTスタイルシートで宣言しさえすれば、あとはXPathでそれを使用して要素を指定するだけで済みます.さてそれでは今まで見てきた言語では、どのようにネームスペース付きのXMLファイルの読み込みをハンドリングするのでしょうか?順に見てゆきたいと思います.