Python的etree.tostring编码问题
我正在使用Python 2.6.2中的xml.etree.cElementTree来创建一个XML文档:
import xml.etree.cElementTree as etree
elem = etree.Element('tag')
elem.text = (u"Würth Elektronik Midcom").encode('utf-8')
xml = etree.tostring(elem,encoding='UTF-8')
最后生成的XML看起来是这样的:
<?xml version='1.0' encoding='UTF-8'?>
<tag>Würth Elektronik Midcom</tag>
看起来tostring函数忽略了编码参数,把'ü'编码成了其他字符编码('ü'是有效的utf-8编码,我很确定)。
如果有人能告诉我我哪里做错了,我将非常感激。
2 个回答
5
etree.tostring(elem, encoding=str)
在Python 3中,这个函数会返回一个str
类型的字符串,而不是binary
类型的。
你还可以通过传入
unicode
函数作为编码(在Python 3中用str
),或者直接使用名称'unicode',来将内容序列化为一个Unicode字符串,而不需要特别声明。这会把返回值从字节字符串变成一个未编码的Unicode字符串。
21
你把文本编码了两次。试试这个:
import xml.etree.cElementTree as etree
elem = etree.Element('tag')
elem.text = u"Würth Elektronik Midcom"
xml = etree.tostring(elem, encoding='UTF-8')