はじめに
Document Object Model(DOM)とは、XML(またはHTML)文書をツリー構造のオブジェクトとして表現するための一連のインターフェースを定めたW3C規格です。DOMツリーは文書の論理的な構造を定義し、プログラムによる文書の操作を制御します。開発者はDOMを使用して、XML文書やHTML文書の作成、ツリー構造内での移動、要素やコンテンツの追加、変更、削除を行うことができます。DOMは任意のプログラミング言語から操作できます。本稿ではPHP 5のDOMエクステンションを使います。これはPHPコアに既に実装されているので、別途インストールすべきものは特にありません。
DOMツリーはXML規約に基づいて命名されたノードで構成されます。よく知られているDOMノードには次のものがあります。
- Documentノード(DOMDocumentインターフェースで表現)
- Elementノード(DOMElementインターフェースで表現)
- Attributeノード(DOMAttrインターフェースで表現)
- Commentノード(DOMCommentインターフェースで表現)
- Textノード(DOMTextインターフェースで表現)
要素を抽出する
DOMツリーから要素と値を抽出する方法を具体的に説明します。本稿で使用するサンプル文書「Book.xml」をリスト1に示します。
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <book> <!--XML Processing [part I] --> <name>XML Processing I</name> <author>John Smith Jr.</author> <publisher>HisOwnTM</publisher> <ISBN>111-222-333-4441</ISBN> <contents> <chapter_I> <title>What is XML about ?</title> <content>XML (Extensible Markup Language) is a ...</content> </chapter_I> <chapter_II> <title>SAX</title> <content>SAX is a simple API for ...</content> </chapter_II> <chapter_III> <title>StAX</title> <content>Much powerful and flexible, StAX, is very...</content> </chapter_III> <chapter_IV> <title>DOM <subtitle>DOM concept <continut>Starting to use DOM...</continut> </subtitle> <subchapter_IV_I> <title>First DOM application...</title> <content>Here it is your first DOM application...</content> </subchapter_IV_I> </title> </chapter_IV> <end>The end...</end> </contents> <!-- See you in XML Processing [part II] --> </book>
以降の説明に従って作業を進めるには、このBook.xmlを本稿のPHPサンプルアプリケーションと同じディレクトリに置いておきます(サンプルアプリケーションは記事先頭のリンクからダウンロード可能)。
最初のアプリケーションではBook.xmlを使って、関連付けられたツリーを抽出し、いくつかの子ノードの最初のオカレンスをDOMElementインターフェースのgetElementsByTagName
メソッドを使って表示します。
DOMNodeList DOMElement::getElementsByTagName(string $name)
このメソッドは、$name
パラメータで指定したタグ名を持つすべての子要素のリストを返します。次の例では、<book>
ルートノードを検索し、そのすべての子要素<author>
、<publisher>
、<name>
を検索して各要素の最初のオカレンスを選択し、それらのノードの値を出力します。
<?php // Create a document instance $doc = new DOMDocument(); //Load the Book.xml file $doc->load( 'Book.xml' ); //Searches for all elements with the "book" tag name $books = $doc->getElementsByTagName( "book" ); //Searches for all elements with the "author" tag name $authors = $doc->getElementsByTagName( "author" ); //Returns the first element found having the tag name "author" $author = $authors->item(0)->nodeValue; //Searches for all elements with the "publisher" tag name $publishers = $doc->getElementsByTagName( "publisher" ); //Returns the first element found //having the tag name "publisher" $publisher = $publishers->item(0)->nodeValue; //Searches for all elements with the "name" tag name $titles = $doc->getElementsByTagName( "name" ); //Returns the first element found having the tag name "name" $title = $titles->item(0)->nodeValue; //Printing the found values echo "$title - $author - $publisher \n"; ?>
最後の行では、検索された最初の書名、最初の著者、最初の出版社をハイフン(-)で区切って出力します。結果は次のようになります。
XML Processing I - John Smith Jr. - HisOwnTM