简体   繁体   中英

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?

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'))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM