問題描述
我正在嘗試使用 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 中不可用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!