使用XPATH通过子节点获取父节点

问题描述 投票:0回答:3

我正在尝试使用

e.find('..)'
访问树中元素的父节点,但它不起作用。对于以下代码:

import xml.etree.ElementTree as etree

xml = "<a> <b> </b> </a>"

root = etree.fromstring(xml)
child = root.find('*')

print(child.find('..'))

输出是:

None
,为什么?而且,我怎样才能得到父元素(在本例中是节点<\a>)?

我已经尝试了不同的路径组合并在互联网上进行了搜索,有些解决方案不起作用,有些是针对该问题的。

python xpath xml-parsing elementtree
3个回答
0
投票

您的代码片段返回

None
,因为根的父级是根本身。


0
投票

使用包含 XPath 1.0 实现的 lxml 库:

>>> import lxml.etree as let
>>> doc = let.fromstring("<a> <b> </b> </a>")
>>> doc.xpath('//*[b]') # return all nodes with a direct `b` child
[<Element a at 0x7fffef3ed8c0>]

-1
投票

可以用 ElementTree 获取父级,但不能直接在子级上使用

find()

文档声明:

..
选择父元素。如果路径试图到达起始元素的祖先(元素
None
被调用),则返回
find

演示:

import xml.etree.ElementTree as etree

xml = "<a> <b> </b> </a>"

root = etree.fromstring(xml)
child = root.find('*')

# This does not work because we are calling find() on the child element
print(child.find('..'))   # None

# This works because we are calling find() on the root element
print(root.find("*/.."))  # <Element 'a' at 0x000002088B2B4B30> 
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.