2

I stumbled across the following XPATH expression applied on a certain root node:

.//*[not(child::*)]

child::* selects all the children nodes of the current node. .//* selects all nodes under the current node (including their children)

As a result, I would intuitively say that the expression selects.. all leaf nodes? ie. nodes that do not have any more children. That is, not(child::*) actually verifies the number of children to be 0.

Let's apply this expression on the root node of the following tree:

<root>
  <A>
    <C/>
    <D/>
    <E>
      <F/>
      <G>
        <H/>
      </G>
    </E>
  </A>
  <B>
    <I>
      <J/>
      <K/>
    </I>
  </B>
</root>

Am I correct when I say that my expression selects C D F H J K?

Sterpu Mihai
  • 486
  • 1
  • 4
  • 15

1 Answers1

2

Yes, you are correct. The expression selects nodes with no child, a.k.a. leaf node. You can test it with an XPath tester like this one.

Code Different
  • 90,614
  • 16
  • 144
  • 163
  • 10x! Is there another "classic" aproach for selecting leaf nodes only? – Sterpu Mihai Jun 03 '16 at 13:20
  • 1
    See [here](http://stackoverflow.com/questions/3926589/how-to-select-all-leaf-nodes-using-xpath-expression) and [here](http://stackoverflow.com/questions/10585027/xpath-matching-leaf-nodes) – Code Different Jun 03 '16 at 13:33
  • 1
    Technically, the expression selects all elements having no child elements. A "node" is not the same thing as an "element". Text nodes, comments, etc are always leaf nodes; and elements containing text are not leaf nodes. – Michael Kay Jun 03 '16 at 14:12