Reputation: 24104
I want to search for a XML node, but limiting the search to a certain depth? What is the expression for that?
For example, I want to find all article
tags, but exclude nested article tags, so only id 1 and 2.
<div id="timeline">
...
<article id="1"> </article>
<article id="2">
...
<article id=3> </article>
</article>
</div>
Upvotes: 2
Views: 336
Reputation: 111621
This XPath,
//article[not(ancestor::article)]
will select all article
elements that have no article
ancestors, so for your example XML, it will only select article
elements with id
attribute values of 1
or 2
.
To more generally limit selection based upon depth (as is asked in your question's title), the number of ancestors can be counted:
//article[count(ancestor::article) < 3]
for those article
elements with less than three article
ancestors.//article[count(ancestor::*) < 3]
for those article
elements with less than three ancestors of any type.//*[count(ancestor::*) < 3]
for any elements with less than three ancestors.Upvotes: 2