0

Can i query multiple attributes from a XML Node by using XPath? Especially from sub-nodes? e.g.

<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"]
]
1

2 Answers 2

1

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. 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"
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this query:

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

This query matches any node that has an atribute starting with attr.

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.