在 PHP 中使用 XPath 提取 XML [英] Using XPath to extract XML in PHP
问题描述
我有以下 XML:
<root>
<level name="level1">
<!-- More children <level> -->
</level>
<level name="level2">
<!-- Some more children <level> -->
</level>
</root>
如何直接在
下提取
以便我可以运行 XPath 查询,例如 $xml->xpath('//some-query')
相对于提取的
?
How can I extract a <level>
directly under <root>
so that I can run an XPath query such as $xml->xpath('//some-query')
relative to the extracted <level>
?
推荐答案
DOMXPath::query 的第二个参数是上下文节点.只需传递您之前找到"的 DOMNode 实例,您的查询就会相对"运行到该节点.例如
DOMXPath::query's second parameter is the context node. Just pass the DOMNode instance you have previously "found" and your query runs "relative" to that node. E.g.
<?php
$doc = new DOMDocument;
$doc->loadxml( data() );
$xpath = new DOMXPath($doc);
$nset = $xpath->query('/root/level[@name="level1"]');
if ( $nset->length < 1 ) {
die('....no such element');
}
else {
$elLevel = $nset->item(0);
foreach( $xpath->query('c', $elLevel) as $elC) {
echo $elC->nodeValue, "\r\n";
}
}
function data() {
return <<< eox
<root>
<level name="level1">
<c>C1</c>
<a>A</a>
<c>C2</c>
<b>B</b>
<c>C3</c>
</level>
<level name="level2">
<!-- Some more children <level> -->
</level>
</root>
eox;
}
<小时>
但是除非您必须执行多个单独的(可能是复杂的)后续查询,否则这很可能没有必要
But unless you have to perform multiple separate (possible complex) subsequent queries, this is most likely not necessary
<?php
$doc = new DOMDocument;
$doc->loadxml( data() );
$xpath = new DOMXPath($doc);
foreach( $xpath->query('/root/level[@name="level1"]/c') as $c ) {
echo $c->nodeValue, "\r\n";
}
function data() {
return <<< eox
<root>
<level name="level1">
<c>C1</c>
<a>A</a>
<c>C2</c>
<b>B</b>
<c>C3</c>
</level>
<level name="level2">
<c>Ahh</c>
<a>ouch</a>
<c>no</c>
<b>wrxl</b>
</level>
</root>
eox;
}
仅使用一个查询即可获得相同的输出.
has the same output using just one query.
这篇关于在 PHP 中使用 XPath 提取 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!