写入文件时出现XML编码错误
我觉得我走的方向是对的,但还是遇到了编码错误:
from xml.dom.minidom import Document
import codecs
doc = Document()
wml = doc.createElement("wml")
doc.appendChild(wml)
property = doc.createElement("property")
wml.appendChild(property)
descriptionNode = doc.createElement("description")
property.appendChild(descriptionNode)
descriptionText = doc.createTextNode(description.decode('ISO-8859-1'))
descriptionNode.appendChild(descriptionText)
file = codecs.open('contentFinal.xml', 'w', encoding='ISO-8859-1')
file.write(doc.toprettyxml())
file.close()
描述节点里有一些字符是用 ISO-8859-1 编码
的,这种编码是网站在元标签里自己指定的。但是当 doc.toprettyxml()
开始写入文件时,我收到了以下错误:
Traceback (most recent call last):
File "main.py", line 467, in <module>
file.write(doc.toprettyxml())
File "C:\Python27\lib\xml\dom\minidom.py", line 60, in toprettyxml
return writer.getvalue()
File "C:\Python27\lib\StringIO.py", line 271, in getvalue
self.buf += ''.join(self.buflist)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 10: ordinal not in range(128)
我为什么会遇到这个错误呢?我不是用同样的标准在解码和编码吗?
编辑
我在我的脚本文件里有以下声明:
#!/usr/bin/python
# -*- coding: utf-8 -*-
这可能会造成冲突吗?
1 个回答
1
好的,我找到了解决办法。当数据是其他外语时,你只需要在XML的头部定义正确的编码就可以了。你不需要在file.write(doc.toprettyxml(encoding='ISO-8859-1'))
中描述编码,甚至在打开文件写入时file = codecs.open('contentFinal.xml', 'w', encoding='ISO-8859-1')
也不需要。下面是我使用的技巧。可能这不是专业的方法,但对我来说有效。
file = codecs.open('abc.xml', 'w')
xm = doc.toprettyxml()
xm = xm.replace('<?xml version="1.0" ?>', '<?xml version="1.0" encoding="ISO-8859-1"?>')
file.write(xm)
file.close()
也许有一种方法可以在头部设置默认编码,但我找不到。上述方法在浏览器中没有出现任何错误,所有数据都显示得很完美。