hey
hey

Reputation: 3242

How to select xml elements by an attribute name containing a colon in PHP (domx)?

Similar to the question here, I am trying to select xml elements by their attribute name, which contains a colon.

I am trying to do this with PHP, and my final goal is, to replace the content of these elements.

My code does not return any result:

$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<a>
<aff xml:id="af1" value="a">
    <uAff>
        Hello
    </uAff>
</aff>
<aff xml:id="corr1">
    <uAff>
        Hello1
    </uAff>
</aff>
</a>';

$dom = new DOMDocument;
$dom->loadHTML($xml);
$xpath = new DOMXPath($dom);

$xelems = $xpath->query("/a/aff/@*[name()='xml:id']");
print_r($xelems);

foreach ($xelems as $node) {
    $node->nodeValue = 'New attribute value'; // changes the value of the xml:id attribute.';
   $node->parentNode->nodeValue = 'This does work!'; // changes the value of the element
}
echo htmlentities($dom->saveHTML());

How can this work with PHP?

Upvotes: 0

Views: 1362

Answers (1)

choroba
choroba

Reputation: 241738

The input is XML, so use loadXML instead of loadHTML.

* selects elements. @* selects attributes.

@*[name()='xml:id']

You might also need to start the expression by // to make it search everywhere, not just under the root node.

But then, much simpler expression might be used:

//@xml:id

or, with the full path

/a/aff/@xml:id

Upvotes: 1

Related Questions