Prasoon Tiwari
Prasoon Tiwari

Reputation: 850

XPath: how to find nodes with only the specified attributes and no other attributes

The following example illustrates my problem:

<nodes>
   <node at1="1" at2="2"> 12 </node>
   <node at1="1" at2="2" at3="3"> 123 </node>
   <node at1="1"> 1 </node>        <-----find this node
</nodes>

/nodes/node[@at1] returns all three nodes, but I am looking for nodes with only the "at1" attribute and no other attributes.

Upvotes: 2

Views: 120

Answers (1)

janos
janos

Reputation: 124648

This finds node having attribute @at1, and no other attributes:

//node[@at1 and count(@*) = 1]

If you want to permit another optional attribute x, you can do like this:

//node[@at1 and count(@*) - count(@x) = 1]

What if you have nodes with xmlns namespace declaration like this:

<nodes>
   <node at1="1"> 1 </node>
   <node at1="2" xmlns="http://xyz"> 2 </node>
</nodes>

You can match both nodes like this:

//*[name()='node' and @at1 and count(@*) = 1]

To match only the node with xmlns:

//*[name()='node' and @at1 and count(@*) = 1 and namespace-uri()='http://xyz']

To match only the node without xmlns:

//*[name()='node' and @at1 and count(@*) = 1 and namespace-uri()='']

Upvotes: 4

Related Questions