在python中将XML写入文件会损坏文件

2024-10-06 12:38:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图将xml.dom.minidom对象中的内容写入文件。简单的想法是使用“writexml”方法:

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文本写入文件?我错过了什么?

编辑。通过添加decode语句修复错误: f.write(xmldoc.toxml("utf-8").decode("utf-8")) 但是俄罗斯的符号仍然被破坏。

文本在解释器中查看时不会损坏,但在文件中写入时会损坏。


Tags: 文件inpy文本linexmlutfencoding