background image

 

清单 1 

 

中的例子用 DOM 解析文档,通过 getElementById 

 

检索一个元素。引用 ID 之

前需要设置 validateOnParse=true 

 

来验证文档。根据 DOM 

 

标准,它要求 DTD 定义

 

一个 ID 

 

类型的属性 ID。

 

清单 1. 

 

使用 DOM 处理基本文档 

<?php

$doc = new DomDocument;

// We must validate the document before referring to the id
$doc->validateOnParse = true;
$doc->Load('basic.xml');

echo "The element whose id is myelement is: " . 
$doc->getElementById('myelement')->tagName . "\n";

?>

getElementsByTagName() 函数返回类

 DOMNodeList 的一个新实例,包含使用给定

标记名的元素。当然这个列表需要遍历。迭代 getElementsByTagName() 返回的 NodeL
ist 的同时修改文档结构,会影响迭代的

 NodeList

 

(参见清单 2)。不需要验证。

 

清单 2. DOM getElementsByTagName 方法

DOMDocument {
 DOMNodeL i s t   getE lementsByTagName(s t r ing  name) ;
}

 

清单 3 

 

中的例子结合使用了 DOM   

和 XPath。

 

清单 3. 

 

使用 DOM   

和 XPath 进行解析

<?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->Load('book.xml');