如果子元素存在,如何在Xpath中获取父元素的属性值?
问题描述:
我是 XPath 的新手,如果存在特定的子元素,我不确定如何获取父元素的属性值.
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>
如果
元素是从元素
获取 @name
属性,我的 XPath 应该是什么?存在于初级?
What should be my XPath to get the @name
attribute from the element <planet>
if the <oxygen>
element is present within primary?
答
您可以使用谓词向下查看树.这将选择所有具有 primary/oxygen
子元素的 planet
元素.我添加了一个根元素,假设它被埋在某个文档中.
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'))