【发布时间】:2009-03-25 21:17:56
【问题描述】:
我做了类似于this 的操作,但找不到将结果写入 xml 文件的方法。
【问题讨论】:
我做了类似于this 的操作,但找不到将结果写入 xml 文件的方法。
【问题讨论】:
您链接到的网页上的代码使用doc.toprettyxml 从 XML DOM 创建一个字符串,因此您可以将该字符串写入文件:
f = open("output.xml", "w")
try:
f.write(doc.toprettyxml(indent=" "))
finally:
f.close()
在 Python 2.6(或者我想是 2.7,无论何时出现),您都可以使用“with”语句:
with open("output.xml", "w") as f:
f.write(doc.toprettyxml(indent=" "))
如果你把这也适用于 Python 2.5
from __future__ import with_statement
在文件的开头。
【讨论】:
coonj 是对的,但 xml.dom.ext.PrettyPrint 是越来越被忽视的 PyXML 扩展包的一部分。如果您想保持在提供的标准 minidom 内,您会说:
f= open('yourfile.xml', 'wb')
doc.writexml(f, encoding= 'utf-8')
f.close()
(或者使用 David 提到的 'with' 语句使其略短。使用模式 'wb' 以避免 Windows 上不需要的 CRLF 换行符干扰 UTF-16 等编码。因为 XML 有自己的处理换行符的机制解释,它应该被视为二进制文件而不是文本。)
如果您不包含“encoding”参数(对于 writexml 或 toprettyxml),它会尝试将 Unicode 字符串直接写入文件,因此如果其中有任何非 ASCII 字符,您会得到一个 UnicodeEncodeError。不要自己尝试 .encode() toprettyxml 的结果;对于非 UTF-8 编码,这可能会生成格式不正确的 XML。
没有“writeprettyxml()”函数,但自己做却很简单:
with open('output.xml', 'wb') as f:
doc.writexml(f, encoding= 'utf-8', indent= ' ', newl= '\n')
【讨论】:
f = open('yourfile.xml', 'w')
xml.dom.ext.PrettyPrint(doc, f)
f.close()
【讨论】: