简体   繁体   English

如果子元素存在,如何在Xpath中获取父元素的属性值?

[英]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. 我是XPath的新手,并且不确定存在特定子元素时如何获取父元素的属性值。

<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? 如果<oxygen>元素存在于主对象中,那么从元素<planet>获取@name属性的XPath应该是什么?

You can use a predicate to look down the tree. 您可以使用谓词向下看树。 This selects all planet elements that have primary/oxygen subelements. 这将选择所有具有primary/oxygen子元素的planet元素。 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 . 正确的答案取决于您当前的XPath轴 So if your current axis is <oxygen> the XPath expression to access the @name attribute of the element <planet> would be: 因此,如果您当前的轴是<oxygen> ,则访问元素<planet>@name属性的XPath表达式将是:

../../@name

Or encapsulated in an XSLT expression: 或封装在XSLT表达式中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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