buttowski
buttowski

Reputation: 4907

How to get the attribute value of a parent element in Xpath if Child element exists?

I'm new to XPath and not sure how to get the attribute value of a parent element if a specific child element exists.

<planet name="Earth" star="Sun">
      <primary>
            <oxygen>20.95%</oxygen>
            <water>70.8%</water>
      </primary>
</planet>

What should be my XPath to get the @name attribute from the element <planet> if the <oxygen> element is present within primary?

Upvotes: 0

Views: 1955

Answers (2)

tdelaney
tdelaney

Reputation: 77347

You can use a predicate to look down the tree. This selects all planet elements that have primary/oxygen subelements. I added a root element assuming this is buried in a document somewhere.

import lxml.etree

doc = lxml.etree.fromstring("""<root>
<planet name="Earth" star="Sun">
      <primary>
            <oxygen>20.95%</oxygen>
            <water>70.8%</water>
      </primary>
</planet>
</root>""")

print(doc.xpath('planet[primary/oxygen]/@name'))

Upvotes: 2

zx485
zx485

Reputation: 29022

The correct answer depends on you current XPath axis. So if your current axis is <oxygen> the XPath expression to access the @name attribute of the element <planet> would be:

../../@name

Or encapsulated in an XSLT expression:

<xsl:value-of select="../../@name" />

Upvotes: -1

Related Questions