ancestor::foo[bar[@attr="val"]]
I thought this would work, but it's not. I need to find the nearest foo
element going up in the tree that has a bar
child element, which in turn has an attr
attribute of val
.
ancestor::foo[bar[@attr="val"]]
I thought this would work, but it's not. I need to find the nearest foo
element going up in the tree that has a bar
child element, which in turn has an attr
attribute of val
.
This should work:
or alternatively
matches the second
<bar>
elementIf you have a file like this:
and you want the
foo
nodes with the ids2
and3
, i.e. the closestfoos
to theirbar
descendants havingattr=val
, the following works:If you omit
and not(descendant::foo)
you get additionally thefoo
with the id0
.The other answers didn't work for me on the general case of my example.
You can test it in Python with:
which prints:
Notice that the xpath used is not efficient. I would love to learn a more efficient one.
In my opinion the best answer was provided by the person who posed the question. His solution was supposed to return all the ancestor foos. He wants only the nearest one which is the one with position()=1, so his xpath expression needs to be slightly amended to:
If he writes that the
ancestor::foo[bar[@attr="val"]]
didn't return anything, so he had some other problem in his xml or in his assumption about the current element of his XPath evaluation context.The other answers (starting with //) do not really answer the question and even if they by chance met the need of someone, so they are not efficient: they choose ALL elements in the xml file, applying filter on them afterwards. While what the relative xpath proposed by me or the person who was asking this question is just going to search through few elements starting from the current node up to the parent and it's parent etc. - it will be very efficient even with large XML files.
Updated to reflect a solution intended by OP.
See @David's answer
For a sample xml below,
a valid xpath on the reverse axis with <three> as the context node, a valid solution is
"./" is optional. position() = 1 is not optional as otherwise the ancestor
foo
satisfying the predicates would also be returned.Old answer:ignore
This is an old question. but anybody who is interested, the following should get you what the original question intended.
Reverse axis
Forward axis