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?

2 Answers 2

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'))
Sign up to request clarification or add additional context in comments.

Comments

-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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.