简体   繁体   English

XPath:查询多个属性

[英]XPath: Query multiple attributes

Can i query multiple attributes from a XML Node by using XPath? 我可以使用XPath从XML节点查询多个属性吗? Especially from sub-nodes? 特别是从子节点? eg 例如

<outer>
  <inner attr1="value1" attr2="value2">
      <leaf attr3="value3" />
  </inner>
  <inner attr1="value1Inner1" attr2="valueInner12">
      <leaf attr3="value_leaf2" />
  </inner>
</outer>

I want to get something like 我想得到像

[
  ["value1", "value2", "value3"],
  ["value1Inner1", "valueInner12", value_leaf2"]
]

Yes, attributes are just nodes. 是的,属性只是节点。 But it can not fetch nested node lists. 但是它无法获取嵌套的节点列表。 So for the desired result you need to select the inner elements first. 因此,要获得理想的结果,您需要首先选择inner元素。 Iterate them and fetch all the attribute from them and their descendants. 迭代它们并从它们及其后代中获取所有属性。

Fetch the `inner? 提取`内部? element nodes: 元素节点:

/outer/inner

And the attributes of the context node and its descendants: 以及上下文节点及其后代的属性:

descendant-or-self::*/@*

Demo: 演示:

$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);
}

Output: 输出:

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"
}

Try this query: 试试这个查询:

//*/@*[starts-with(name(), 'attr')]

This query matches any node that has an atribute starting with attr . 该查询匹配具有attr开头的attr任何节点。

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM