André
André

Reputation: 307

Get nodes with unique attribute value

I want to clean an XML file, and don't allow nodes to have an attribute with the same value. The XML looks like :

<bar>
  <foo id="123" some="attribute"/>
  <foo id="abc" some="other attribute"/>
  <foo id="123" some="different attribute"/>
</bar>

and it should look like :

<bar>
  <foo id="abc" some="other attribute"/>
  <foo id="123" some="different attribute"/>
</bar>

I am using PHP but I don't want to make many loops, so I thought of using an XPath request with the DOMXPath object. I have found that the Xpath distinct-values function could help but as far as I understand, it just works for duplicate nodes, not for nodes duplicate attributes.

Is there a solution in XPath, or even a great algorithm in PHP?

Upvotes: 1

Views: 271

Answers (1)

Jirka Š.
Jirka Š.

Reputation: 3428

Try following xpath

/bar/foo[not(@id = following-sibling::foo/@id)]

I didn't test it very much since you provided only few test data but I think it could work.

Upvotes: 2

Related Questions