<p>在我看来,<code>ElementTree</code>是一个不错的选择。如果将来需要更强大的包,可以切换到使用相同接口的第三方<code>lxml</code>模块。</p>
<p>您的问题的答案可以在文档<a href="http://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write" rel="nofollow">http://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write</a>中找到</p>
<blockquote>
<p>The output is either a string (str) or binary (bytes). This is controlled by the encoding argument. If encoding is "unicode", the output is a string; otherwise, it’s binary. Note that this may conflict with the type of file if it’s an open file object; make sure you do not try to write a string to a binary stream and vice versa.</p>
</blockquote>
<p>基本上,你做得对。以文本模式<code>open()</code>文件,这样文件接受字符串,并且需要使用<code>'unicode'</code>参数作为<code>tree.write()</code>。否则,可以以二进制模式打开文件(在<code>open()</code>中没有编码参数),并在<code>tree.write()</code>中使用<code>'utf-8'</code>。</p>
<p>稍微清理一下独立工作的代码:</p>
<pre><code>#!python3
from xml.etree import ElementTree as et
def dict_to_elem(dictionary):
item = et.Element('Item')
for key in dictionary:
field = et.Element(key.replace(' ',''))
field.text = dictionary[key]
item.append(field)
return item
root = et.Element('AllItems') # create the element first...
tree = et.ElementTree(root) # and pass it to the created tree
root.append(dict_to_elem( {'some_tag':'Hello World', 'xxx': 'yyy'} ))
# Lather, rinse, repeat this append step as needed
filename = 'a.xml'
with open(filename, 'w', encoding='utf-8') as file:
tree.write(file, encoding='unicode')
# The alternative is...
fname = 'b.xml'
with open(fname, 'wb') as f:
tree.write(f, encoding='utf-8')
</code></pre>
<p>这取决于目的。在这两个问题中,我个人更喜欢第一个解决方案。它清楚地表明您编写了一个文本文件(而XML是一个文本文件)。</p>
<p>但不需要告诉编码的最简单的替代方法是将文件名传递给<code>tree.write</code>,如下所示:</p>
<pre><code>tree.write('c.xml', encoding='utf-8')
</code></pre>
<p>它打开文件,使用给定的编码写入内容,然后关闭文件。你读起来很容易,在这里也不会出错。</p>