安装
pip install xml
示例
python
# -*- coding: utf-8 -*-
from xml.dom import minidom
# 待美化的xml
ugly_xml= '<Users><User name="Tom" /><User name="Tack" /></Users>'
# 解析为xml对象
parse_xml = minidom.parseString(ugly_xml)
# 美化输出,指定编码为UTF-8,缩进为2个空格
xml_pretty_str = parse_xml.toprettyxml(encoding='UTF-8', indent=" ")
print(xml_pretty_str.decode())
输出结果
xml
<?xml version="1.0" encoding="UTF-8"?>
<Users>
<User name="Tom"/>
<User name="Tack"/>
</Users>
参考