【发布时间】:2017-04-25 13:34:32
【问题描述】:
有人知道为什么这段代码没问题:
text='''<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
</data>'''
root=ET.fromstring(text)
ET.tostring(root, method='xml')
ET.tostring(root, encoding='UTF-8', method='xml')
但是当我使用 Unicode 编码时:
ET.tostring(root, encoding='Unicode', method='xml')
我明白了:
Traceback (most recent call last):
... omissis ...
File "/home/ago/anaconda3/lib/python3.6/xml/etree/ElementTree.py", line 915, in _serialize_xml
write("<" + tag)
TypeError: a bytes-like object is required, not 'str'
TypeError: a bytes-like object is required, not 'str'
根据带有 tostring 的 python 3.6 doc 我可以使用 'Unicode' ...
"使用 encoding="unicode" 生成一个 Unicode 字符串(否则,一个 bytestring 生成)。”
我可以毫无问题地使用ElementTree.write(... encoding='Unicode' ...)。
我用:
Python 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 12:22:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
与
Python 3.4.2 (default, Oct 8 2014, 10:45:20)
[GCC 4.9.1] on linux
我有不同的行为:
ET.tostring(root, encoding='Unicode')
Traceback (most recent call last):
... omissis ...
File "/usr/lib/python3.4/xml/etree/ElementTree.py", line 917, in _serialize_xml
write("<" + tag)
TypeError: 'str' does not support the buffer interface
提前致谢
【问题讨论】:
-
如果您使用
encoding='unicode'(小写“u”),错误就会消失,不是吗? -
宾果游戏!感谢 mzjn,我误读了我在问题中引用的内容:“使用 encoding="unicode" 生成 Unicode 字符串(否则会生成一个字节串)。” ... ElementTree.write() 使用
enc_lower = encoding.lower()降低字符串。即使 tostring 似乎调用 ElementTree.write,它的工作方式也不同。我将深入研究 ET 代码...
标签: python elementtree