Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select descendant elements that are not contained in another type of element

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.

like image 937
Tobia Avatar asked Aug 28 '15 13:08

Tobia


People also ask

What are used to select related or descendant elements?

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.

What is descendant selectors?

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.

What character is used to indicate direct descendant combinator?

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.

What does descendant mean in xpath?

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.


1 Answers

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.

like image 179
har07 Avatar answered Nov 15 '22 09:11

har07