Python: xPath not available in ElementTree(Python:XPath 在 ElementTree 中不可用)
问题描述
我正在尝试使用 ElementTree 的 iterparse() 解析 iTunes 播放列表,但出现以下错误:
I am trying to parse iTunes Playlist by using iterparse() of ElementTree but getting following error:
AttributeError: 'Element' object has no attribute 'xpath'
代码如下:
import xml.etree.ElementTree as ET
context = ET.iterparse(file,events=("start", "end"))
# turn it into an iterator
context = iter(context)
# get the root element
event, root = context.next()
for event, elem in context:
z = elem.xpath(".//key")
elem.clear()
root.clear()
print z
我做错了什么?文件太大,所以我必须使用 iterparse().
What I am doing wrong? File is too big so I have to use iterparse() anyway.
推荐答案
xml.etree.ElementTree 对 XPath 表达式提供有限的支持 为其 Element 类 查找,findall 和 findtext 方法(没有 xpath 方法:这就是您收到错误的原因).
xml.etree.ElementTree provides limited support for XPath expressions for its Element class find, findall and findtext methods (there's no xpath method: that's why you are getting an error).
此外,如果您在元素上调用 clear() 以节省使用的内存,则只需在完成处理该元素及其所有元素之后 执行此操作孩子们.
Also, if you call clear() on an element to conserve used memory, you need to do it only after you've finished processing the element and all its children.
因此,您需要将代码更改为类似于以下内容:
Therefore, you need to to change your code to something similar to the following:
for event, elem in context:
for child in elem.findall(".//key"):
# process child
elem.clear()
root.clear()
这篇关于Python:XPath 在 ElementTree 中不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:XPath 在 ElementTree 中不可用
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
