How to select all leaf nodes using XPath expression?

newman picture newman · Oct 13, 2010 · Viewed 23.6k times · Source

I believe it's possible but couldn't figure out the syntax. Something like this:

xmlNode.SelectNodes("//*[count(child::*) <= 1]")

but this is not correct.

Answer

Dimitre Novatchev picture Dimitre Novatchev · Oct 13, 2010

Use:

//node()[not(node())]

In case only element leaf nodes are wanted (and this needs clarification -- are elements that have non-element children considered leaf nodes?), then the following XPath expression selects them:

//*[not(*)]

Both expressions above are probably the shortest that select the desired nodes (either any-node or element -- leaf nodes).