tags:

views:

550

answers:

2

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

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

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

..[@b]

that would return element a. The returned element must be the parent node of a, and should not contain any of a's siblings.

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

+1  A: 

I don't know about the lxml.etree library but ..[@b] is fully valid XPath (Update: see Ben Blank's comment). Identical to parent::a[@b], it will return context at the a element.

eddiegroves
Adjusting to the parent::a[@b] format works nicely. Thank you.
James Kassemi
@eddiegroves — "..[@b]" is *not* valid XPath. You cannot combine the . or .. shorthands with a predicate.
Ben Blank
+1  A: 

You can't combine the . or .. shorthands with a predicate. Instead, you'll need to use the full parent:: axis. The following should work for you:

parent::*[@b]

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

Ben Blank