0

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?

buttowski
  • 4,657
  • 8
  • 27
  • 33

2 Answers2

2

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'))
tdelaney
  • 73,364
  • 6
  • 83
  • 116
-1

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" />
zx485
  • 28,498
  • 28
  • 50
  • 59