w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Find the first ancestor node with X attribute using XPath

You could do it in two steps. First evaluate

count(ancestor-or-self::div[@data-model = 'user'])

as a number, with the current div as the context node. Then take that number $n and evaluate

.//input[count(ancestor::div[@data-model = 'user']) = $n]

The idea here is to find all descendant input elements that have the same number of containing data-model="user" divs as the context node we started from (inclusive).

From XSLT you could do this in a single pass because you have access to the current() function which lets you "escape" from the predicate

.//input[count(ancestor::div[@data-model = 'user']) = 
  count(current()/ancestor-or-self::div[@data-model = 'user'])]

This function isn't available in pure XPath but if your library lets you pass variable bindings to your expressions then you could provide the context node in a variable and use that in place of current().

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.