python 如何将xml文件保存到磁盘?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/683494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save an xml file to disk?
提问by Joan Venge
回答by David Z
The code on the web page you linked to uses doc.toprettyxml
to create a string from the XML DOM, so you can just write that string to a file:
您链接到的网页上的代码用于doc.toprettyxml
从 XML DOM 创建字符串,因此您可以将该字符串写入文件:
f = open("output.xml", "w")
try:
f.write(doc.toprettyxml(indent=" "))
finally:
f.close()
In Python 2.6 (or 2.7 I suppose, whenever it comes out), you can use the "with
" statement:
在 Python 2.6(或 2.7 我想,无论何时出现)中,您都可以使用“ with
”语句:
with open("output.xml", "w") as f:
f.write(doc.toprettyxml(indent=" "))
This also works in Python 2.5 if you put
如果你把这也适用于 Python 2.5
from __future__ import with_statement
at the beginning of the file.
在文件的开头。
回答by bobince
coonj is kind of right, but xml.dom.ext.PrettyPrint is part of the increasingly neglected PyXML extension package. If you want to stay within the supplied-as-standard minidom, you'd say:
coonj 是对的,但 xml.dom.ext.PrettyPrint 是越来越被忽视的 PyXML 扩展包的一部分。如果你想留在提供的标准 minidom 内,你会说:
f= open('yourfile.xml', 'wb')
doc.writexml(f, encoding= 'utf-8')
f.close()
(Or using the ‘with' statement as mentioned by David to make it slightly shorter. Use mode 'wb' to avoid unwanted CRLF newlines on Windows interfering with encodings like UTF-16. Because XML has its own mechanisms for handling newline interpretation, it should be treated as a binary file rather than text.)
(或者使用 David 提到的 'with' 语句使其稍微短一些。使用模式 'wb' 避免 Windows 上不需要的 CRLF 换行符干扰像 UTF-16 这样的编码。因为 XML 有自己的处理换行符解释的机制,它应该被视为二进制文件而不是文本。)
If you don't include the ‘encoding' argument (to either writexml or toprettyxml), it'll try to write a Unicode string direct to the file, so if there are any non-ASCII characters in it, you'll get a UnicodeEncodeError. Don't try to .encode() the results of toprettyxml yourself; for non-UTF-8 encodings this can generate non-well-formed XML.
如果您不包括'encoding' 参数(写入xml 或toprettyxml),它会尝试将Unicode 字符串直接写入文件,因此如果其中有任何非ASCII 字符,您将得到一个Unicode 编码错误。不要尝试自己对 toprettyxml 的结果进行 .encode() 编码;对于非 UTF-8 编码,这可能会生成格式不正确的 XML。
There's no ‘writeprettyxml()' function, but it's trivially simple to do it yourself:
没有 'writeprettyxml()' 函数,但是自己做很简单:
with open('output.xml', 'wb') as f:
doc.writexml(f, encoding= 'utf-8', indent= ' ', newl= '\n')
回答by Jason Coon
f = open('yourfile.xml', 'w')
xml.dom.ext.PrettyPrint(doc, f)
f.close()