106

Using XPath, how to select nodes which have no attributes (where attribute count = 0)?

For example:

<nodes>
    <node attribute1="aaaa"></node>
    <node attribute1="bbbb"></node>
    <node></node> <- FIND THIS
</nodes>
FabienB
  • 1,104
  • 2
  • 11
  • 22
Zanoni
  • 30,028
  • 13
  • 53
  • 73

3 Answers3

173
//node[not(@*)]

That's the XPath to select all nodes named "node" in the document without any attributes.

48klocs
  • 6,073
  • 3
  • 27
  • 34
  • 1
    This is nice, but it still finds `` anything we can do about it? – Marek Apr 14 '16 at 07:57
  • 1
    @MarekCzaplicki see answer below to address this case. https://stackoverflow.com/questions/1323755/xpath-how-to-select-nodes-which-have-no-attributes/43910689#43910689 – phil May 11 '17 at 08:49
24
//node[count(@*)=0]

Will select all <node> with zero attributes

erik
  • 1,238
  • 3
  • 12
  • 23
11

To address Marek Czaplicki's comment and expand the answer

//node[not(@*) or not(string-length(@*))]

....will select all node elements with zero attributes OR which have attributes that are all empty. If it was just a particular attribute you are interested in, rather than all of them, then you could use

//node[not(@attribute1) or not(string-length(@attribute1))]

...and this would select all node elements that either don't have an attribute called attribute1 OR which have an attribute1 attribute that is empty.

That is, the following elements would be picked out by either of these xpath expressions

<nodes>
    <node attribute1="aaaa"></node>
    <node attribute1=""></node> <!--This one -->
    <node attribute1="bbbb"></node>
    <node></node> <!--...and this one -->
</nodes>

See jsfiddle example here

phil
  • 879
  • 1
  • 10
  • 20