Python 使用 xml.etree.ElementTree 打印格式良好的 xml 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17402323/
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
Use xml.etree.ElementTree to print nicely formatted xml files
提问by TheBeardedBerry
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.
我正在尝试使用xml.etree.ElementTree
Python 写出 xml 文件。问题是它们一直在一行中生成。我希望能够轻松引用它们,因此如果可能的话,我真的希望能够干净地写出文件。
This is what I am getting:
这就是我得到的:
<Language><En><Port>Port</Port><UserName>UserName</UserName></En><Ch><Port>IP地址</Port><UserName>用户名称</UserName></Ch></Language>
This is what I would like to see:
这是我想看到的:
<Language>
<En>
<Port>Port</Port>
<UserName>UserName</UserName>
</En>
<Ch>
<Port>IP地址</Port>
<UserName>用户名称</UserName>
</Ch>
</Language>
采纳答案by Maxime Chéramy
You can use the function toprettyxml()
from xml.dom.minidom
in order to do that:
您可以使用toprettyxml()
from函数xml.dom.minidom
来执行此操作:
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")
The idea is to print your Element
in a string, parse it using minidom and convert it again in XML using the toprettyxml
function.
这个想法是Element
在一个字符串中打印你的,使用 minidom 解析它并使用该toprettyxml
函数在 XML 中再次转换它。
Source: http://pymotw.com/2/xml/etree/ElementTree/create.html
回答by user151019
You could use the library lxml(Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print- for example:
您可以使用库lxml(注意顶级链接现在是垃圾邮件),它是 ElementTree 的超集。它的 tostring() 方法包含一个参数pretty_print- 例如:
>>> print(etree.tostring(root, pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>