Xpath 实际上知道哪个元素是根元素,无论您在哪个元素上执行它。示例
<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<b>
<c>code</c>
</b>
</a>
XML;
header('content-type: text/plain');
$xml = new SimpleXMLElement($string);
$b0=$xml->b[0]->xpath('//c');
while(list( , $node) = each($b0)) {
echo 'b[0]: //c: ',$node,"\n";
}
$b1=$xml->b[1]->xpath('//c');
while(list( , $node) = each($b1)) {
echo 'b[1]: //c: ',$node,"\n";
}
echo "\n";
$b0=$xml->b[0]->xpath('.//c');
while(list( , $node) = each($b0)) {
echo 'b[0]: .//c: ',$node,"\n";
}
$b1=$xml->b[1]->xpath('.//c');
while(list( , $node) = each($b1)) {
echo 'b[1]: .//c: ',$node,"\n";
}
?>
将返回
b[0]: //c: text
b[0]: //c: stuff
b[0]: //c: code
b[1]: //c: text
b[1]: //c: stuff
b[1]: //c: code
b[0]: .//c: text
b[0]: .//c: stuff
b[1]: .//c: code