【发布时间】:2011-03-25 23:59:04
【问题描述】:
我正在尝试迁移到 Python 2.7,由于 Unicode 在那里很重要,我会尝试使用 XML 文件和文本处理它们,并使用 xml.etree.cElementTree 库解析它们。但是我遇到了这个错误:
>>> import xml.etree.cElementTree as ET
>>> from io import StringIO
>>> source = """\
... <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
... <root>
... <Parent>
... <Child>
... <Element>Text</Element>
... </Child>
... </Parent>
... </root>
... """
>>> srcbuf = StringIO(source.decode('utf-8'))
>>> doc = ET.parse(srcbuf)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 56, in parse
File "<string>", line 35, in parse
cElementTree.ParseError: no element found: line 1, column 0
使用io.open('filename.xml', encoding='utf-8') 传递给ET.parse 也会发生同样的事情:
>>> with io.open('test.xml', mode='w', encoding='utf-8') as fp:
... fp.write(source.decode('utf-8'))
...
150L
>>> with io.open('test.xml', mode='r', encoding='utf-8') as fp:
... fp.read()
...
u'<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>\n<root>\n <Parent>\n
<Child>\n <Element>Text</Element>\n </Child>\n </Parent>\n</root>\n
'
>>> with io.open('test.xml', mode='r', encoding='utf-8') as fp:
... ET.parse(fp)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<string>", line 56, in parse
File "<string>", line 35, in parse
cElementTree.ParseError: no element found: line 1, column 0
我在这里缺少关于 unicode 和 ET 解析的内容吗?
edit:显然,ET 解析器不能很好地处理 unicode 输入流?以下作品:
>>> with io.open('test.xml', mode='rb') as fp:
... ET.parse(fp)
...
<ElementTree object at 0x0180BC10>
但这也意味着如果我想解析内存中的文本,我不能使用io.StringIO,除非我先将它编码到内存缓冲区中?
【问题讨论】:
标签: python xml unicode python-3.x