为什么 ElementTree.iterparse() 会引发 ParseError?

发布于 2024-12-08 14:05:27 字数 889 浏览 0 评论 0原文

import xml.etree.ElementTree as ET
xmldata = file('my_xml_file.xml')

tree = ET.parse(xmldata)
root = tree.getroot()
root_iter = root.iter()

现在我可以调用 root_iter.next() 并获取我的 Element 对象。问题是我正在使用的实际文件很大,我无法将其全部放入内存中。所以我尝试使用:

parse_iter = ET.iterparse(xmldata)

如果我调用 parse_iter.next() 它会引发以下问题

Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    parse_iter.next()
  File "C:\Python27\lib\xml\etree\ElementTree.py", line 1260, in next
    self._root = self._parser.close()
  File "C:\Python27\lib\xml\etree\ElementTree.py", line 1636, in close
    self._raiseerror(v)
  File "C:\Python27\lib\xml\etree\ElementTree.py", line 1488, in _raiseerror
    raise err
ParseError: no element found: line 1, column 0

我做错了什么?

import xml.etree.ElementTree as ET
xmldata = file('my_xml_file.xml')

tree = ET.parse(xmldata)
root = tree.getroot()
root_iter = root.iter()

Now I can call root_iter.next() and get my Element objects. The problem is the real file I am working with is huge and I can't fit all of it in memory. So I am trying to use:

parse_iter = ET.iterparse(xmldata)

If I call parse_iter.next() it raises the following

Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    parse_iter.next()
  File "C:\Python27\lib\xml\etree\ElementTree.py", line 1260, in next
    self._root = self._parser.close()
  File "C:\Python27\lib\xml\etree\ElementTree.py", line 1636, in close
    self._raiseerror(v)
  File "C:\Python27\lib\xml\etree\ElementTree.py", line 1488, in _raiseerror
    raise err
ParseError: no element found: line 1, column 0

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧伤还要旧人安 2024-12-15 14:05:27

我的代码非常好,除了我在已经使用 ElementTree.parse() 读取的文件对象上调用 ElementTree.iterparse() 。噢!

在此处输入图像描述

因此,对于那些碰巧犯同样错误的人,解决方案是打开一个新的文件对象或使用 file.seek(0)重置文件光标。

The code I had was perfectly fine, except I was calling ElementTree.iterparse() on a file object I had already read with ElementTree.parse(). D'oh!

enter image description here

So for those who happen to make the same mistake, the solution is to either open a new file object or use file.seek(0) to reset the file cursor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文