In XPath 1.0, how can I select all descendant nodes C of current (context) node A, that are not contained in an intervening node of type B?
For example, find all <a>
links contained in the current element, that are not inside a <p>
. But if the current element is itself inside a <p>
, that's irrelevant.
<p> <—— this is irrelevant, because it's outside the current element
...
<div> <—— current element (context node)
...
<a></a> <—— the xpath should select this node
...
<p>
...
<a></a> <—— but not this, because it's inside a p, which is inside context
...
<p>
...
</div>
...
</p>
The ...
in the example could be several depths of intervening nodes.
I'm writing XSLT 1.0, so the additional functions generate-id()
, current()
, and such are available.
Descendant selectors are used to select elements that are descendants of another element in the document tree. However, if you use a descendant selector, you can refine the <em> elements that you select.
The descendant selector is a way to select elements that are located somewhere underneath other elements, according to the tree structure of the webpage. This selector is actually multiple selectors combined together, but separated by a space.
The descendant combinator — typically represented by a single space (" ") character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc.) element matching the first selector.
The descendant axis indicates all of the children of the context node, and all of their children, and so forth. Attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.
This is one possible XPath :
.//a[not(ancestor::p/ancestor::* = current())]
This XPath checks if current descendant a
element doesn't have ancestor p
which ancestor is current context node. In other words, it checks if the a
element doesn't have ancestor p
intervening between the a
and the current context node.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With