Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all leaf nodes using XPath expression?

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.

like image 532
newman Avatar asked Oct 13 '10 18:10

newman


People also ask

How do you find the XPath of an nth element?

By adding square brackets with index. By using position () method in xpath.

How many types of nodes are there in XPath specification?

In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document nodes. XML documents are treated as trees of nodes. The topmost element of the tree is called the root element.

What is current node in XPath?

Current node is the node that the XPath processor is looking at when it begins evaluation of a query. In other words, the current node is the first context node that the XPath processor uses when it starts to execute the query. During evaluation of a query, the current node does not change.


2 Answers

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).

like image 159
Dimitre Novatchev Avatar answered Sep 29 '22 12:09

Dimitre Novatchev


Any elements with no element child

//*[not(child::*)] 
like image 29
kevpie Avatar answered Sep 29 '22 12:09

kevpie