我正在尝试将xml.dom.minidom
对象中的内容写入文件。简单的想法是使用'writexml'方法:在python中写入XML文件损坏文件
import codecs
def write_xml_native():
# Building DOM from XML
xmldoc = minidom.parse('semio2.xml')
f = codecs.open('codified.xml', mode='w', encoding='utf-8')
# Using native writexml() method to write
xmldoc.writexml(f, encoding="utf=8")
f.close()
问题是它破坏了文件中的非拉丁文编码文本。另一种方式是让文本字符串,并将其写入到文件中明确:
def write_xml():
# Building DOM from XML
xmldoc = minidom.parse('semio2.xml')
# Opening file for writing UTF-8, which is XML's default encoding
f = codecs.open('codified3.xml', mode='w', encoding='utf-8')
# Writing XML in UTF-8 encoding, as recommended in the documentation
f.write(xmldoc.toxml("utf-8"))
f.close()
这将导致以下错误:
Traceback (most recent call last):
File "D:\Projects\Semio\semioparser.py", line 45, in <module>
write_xml()
File "D:\Projects\Semio\semioparser.py", line 42, in write_xml
f.write(xmldoc.toxml(encoding="utf-8"))
File "C:\Python26\lib\codecs.py", line 686, in write
return self.writer.write(data)
File "C:\Python26\lib\codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 2064: ordinal not in range(128)
如何编写一个XML文本文件?我错过了什么?
编辑。错误通过添加解码语句来解决: f.write(xmldoc.toxml("utf-8").decode("utf-8"))
但是,俄罗斯符号仍然损坏。
在解释器中查看文本时,文本没有被破坏,但是在文件中写入文本时。
只是一个想法:你确定您没有错误地查看文件?也许读者期待的是另一种编码,而不是utf-8,它看起来像是borked。 – Nubsis 2010-12-29 12:28:11
@Nubsis这正是发生了什么事情。观众一直期待着ASCII编码。我会保持线程,因为使用.decode()也是问题。谢谢! – martinthenext 2011-01-09 19:08:08