使用xml.etree.ElementTree打印格式正确的xml文件 [英] Use xml.etree.ElementTree to print nicely formatted xml files
问题描述
我正在尝试使用 xml.etree.ElementTree
用Python写出xml文件。问题在于它们总是在一行中生成。我希望能够轻松地引用它们,因此,如果可能的话,我真的很希望能够将文件整洁地写出来。
I am trying to use xml.etree.ElementTree
to write out xml files with Python. The issue is that they keep getting generated in a single line. I want to be able to easily reference them so if it's possible I would really like to be able to have the file written out cleanly.
这就是我得到的:
<Language><En><Port>Port</Port><UserName>UserName</UserName></En><Ch><Port>IP地址</Port><UserName>用户名称</UserName></Ch></Language>
这就是我想看到的:
<Language>
<En>
<Port>Port</Port>
<UserName>UserName</UserName>
</En>
<Ch>
<Port>IP地址</Port>
<UserName>用户名称</UserName>
</Ch>
</Language>
推荐答案
您可以使用函数 toprettyxml()
来自 xml.dom .minidom
为此:
You can use the function toprettyxml()
from xml.dom.minidom
in order to do that:
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
想法是将 Element
打印为字符串,使用minidom进行解析,然后使用 toprettyxml
再次将其转换为XML。函数。
The idea is to print your Element
in a string, parse it using minidom and convert it again in XML using the toprettyxml
function.
来源: http://pymotw.com/2/xml/etree/ElementTree/ create.html
这篇关于使用xml.etree.ElementTree打印格式正确的xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!