本文介绍了如果子元素存在,如何在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'))
这篇关于如果子元素存在,如何在Xpath中获取父元素的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!