我可以使用XPath从XML节点查询多个属性吗? 特别是从子节点? e.g。
<outer>
<inner attr1="value1" attr2="value2">
<leaf attr3="value3" />
</inner>
<inner attr1="value1Inner1" attr2="valueInner12">
<leaf attr3="value_leaf2" />
</inner>
</outer>
我希望得到像
这样的东西[
["value1", "value2", "value3"],
["value1Inner1", "valueInner12", value_leaf2"]
]
答案 0 :(得分:1)
是的,属性只是节点。但它无法获取嵌套节点列表。因此,对于期望的结果,您需要首先选择inner
元素。迭代它们并从它们及其后代中获取所有属性。
取内心?元素节点:
/outer/inner
上下文节点及其后代的属性:
descendant-or-self::*/@*
演示:
$xml = <<<'XML'
<outer>
<inner attr1="value1" attr2="value2">
<leaf attr3="value3" />
</inner>
<inner attr1="value1Inner1" attr2="valueInner12">
<leaf attr3="value_leaf2" />
</inner>
</outer>
XML;
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
foreach ($xpath->evaluate('/outer/inner') as $inner) {
$attributes = array_map(
function (DOMAttr $node) {
return $node->value;
},
iterator_to_array(
$xpath->evaluate('descendant-or-self::*/@*', $inner)
)
);
var_dump($attributes);
}
输出:
array(3) {
[0]=>
string(6) "value1"
[1]=>
string(6) "value2"
[2]=>
string(6) "value3"
}
array(3) {
[0]=>
string(12) "value1Inner1"
[1]=>
string(12) "valueInner12"
[2]=>
string(11) "value_leaf2"
}
答案 1 :(得分:0)