python - 元素树python中具有属性的xpath表达式

标签 python elementtree

import xml.etree.ElementTree as ET
tree: ET = ET.parse(file)
tree.find('.//ns1:tag/@someattribute', ns) 

导致 {KeyError}'@',据我所知,xpath 表达式是正确的,元素树中是否有任何方法可以直接使用 xpath 而不是使用 获取属性值。属性

最佳答案

XPath 表达式在语法上是正确的。问题是 find() 只定位元素。它不能用于查找属性。

这应该有效:

attr = tree.find('.//ns1:tag', ns).get('someattribute')

lxml ,您可以使用 xpath() 方法(返回一个列表):

attr = tree.xpath('.//ns1:tag/@someattribute', namespaces=ns)[0]

关于python - 元素树python中具有属性的xpath表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58077551/

相关文章:

python - nltk tagged_words 意外参数

python - 为什么调用文件 write() 方法不起作用?

python - 使用 ElementTree 在 XML 文件中设置属性值

python - 使用 etree 从所有元素中删除所有数据属性

python - 如何在 lxml 中使用带有 find/findall 的 xml 命名空间?

python - 用循环更新字典

python - 在 Python 中下载文件

python - 为什么将 `tf.while_loop` 中的常量 i 用作 `loop_vars` ?

python - 使用 ElementTree 读取 .xml 等电子表格

python - 使用 Python 仅将 xml 声明写入文件