python – 用ElementTree写入带有utf-8数据的xml utf-8文件

我试图使用ElementTree使用utf-8编码的数据编写一个xml文件,如下所示:

#!/usr/bin/python                                                                       
# -*- coding: utf-8 -*-                                                                   

import xml.etree.ElementTree as ET
import codecs

testtag = ET.Element('unicodetag')
testtag.text = u'Treboda' #The o is really ö (o with two dots over). No idea why SO dont display this
expfile = codecs.open('testunicode.xml',"w","utf-8-sig")
ET.ElementTree(testtag).write(expfile,encoding="UTF-8",xml_declaration=True)
expfile.close()

这样会产生错误

Traceback (most recent call last):
  File "unicodetest.py",line 10,in <module>
    ET.ElementTree(testtag).write(expfile,xml_declaration=True)
  File "/usr/lib/python2.7/xml/etree/ElementTree.py",line 815,in write
    serialize(write,self._root,encoding,qnames,namespaces)    
  File "/usr/lib/python2.7/xml/etree/ElementTree.py",line 932,in _serialize_xml
    write(_escape_cdata(text,encoding))
  File "/usr/lib/python2.7/codecs.py",line 691,in write
    return self.writer.write(data)
  File "/usr/lib/python2.7/codecs.py",line 351,in write
    data,consumed = self.encode(object,self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)

使用“us-ascii”编码代替工作正常,但不保留数据中的unicode字符.发生什么事?

解决方法

codecs.open希望将Unicode字符串写入文件对象,它将处理UTF-8的编码. ElementTree的写入将Unicode字符串编码为UTF-8字节字符串,然后将其发送到文件对象.由于文件对象需要Unicode字符串,所以使用默认的ascii编解码器将字节串强制转换为Unicode,并导致UnicodeDecodeError.

只要这样做:

#expfile = codecs.open('testunicode.xml',"utf-8-sig")
ET.ElementTree(testtag).write('testunicode.xml',xml_declaration=True)
#expfile.close()

dawei

【声明】:淮南站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。