XPath - How can I query the parent node that satisfies the condition of the attribute being present?

I need to query a node to determine if it has a parent node that contains the specified attribute. For instance:

<a b="value">
    <b/>
</a>

      

From element b as my focus, I would like to execute an XPath query:

..[@b]

      

which returns the element a . The returned element must be the parent of node a and must not contain any of the strong members of a .

The lxml.etree library states that this is an invalid XPath expression.

+1


a source to share


2 answers


You cannot combine straight .

or ..

predicate. Instead, you will need to use the full axis parent::

. The following should work for you:

parent::*[@b]

      



This will select the parent node (regardless of its local name), IFF has a "b" attribute.

+4


a source


I don't know about the lxml.etree library, but ..[@b]

is a fully valid XPath ( Update : see Ben Blank's comment). Identical for parent::a[@b]

, it will return the context on the element a

.



+1


a source







All Articles