background image

$xpath = new DOMXPath($doc);

// We start from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
 echo  "Found  {$ent ry - >prev iousS ib l i ng - >prev iousS ib l ing - >nodeVa lue} , "   .
 "   by  {$ent ry - >prev iousS ib l ing - >nodeVa lue} \n" ;
}
?>

 

说了 DOM 

 

的这么多优点之后,为了强调我的观点,最后再给出一个错误使用 DOM 的

 

例子,然后在后面的例子中解决这个问题。清单 4 中的例子将一个很大的文件加载到 
DOM 

 

中,只是为了用 DomXpath 从一个属性中提取数据。

 

清单 4. 

 

错误使用 DOM   

和 XPath

 

,用于大型 XML 文档

<?php

// Parsing a Large Document with DOM and DomXpath
// First create a new DOM document to parse
$dom = new DomDocument();

// This document is huge and we don't really need anything from the tree
// This huge document uses a huge amount of memory 
$dom->load("tooBig.xml");
$xp = new DomXPath($dom);
$result = $xp->query("/blog/entries/entry[@ID = 5225]/title") ;
print $result->item(0)->nodeValue ."\n";

?>

 

后面清单 5 

 

中的例子仍然使用 DOM   

和 XPath

 

,但每次让 XMLReader 用 expand() 传

递一个元素的数据。通过这种方法就能将 XMLReader 传递的节点转换成 DOMElement。

 

清单 5. 

 

正确使用 DOM   

和 XPath

 

,用于大型 XML 文档

<?php