利用文件夹中
C:\Python38\Lib\xml\dom
中有一个minidom.py 中的方法。
1. 把内存中的根节点 root, 利用ET.tostring 转换成紧凑型的string
2. 利用minidom中parseString的方法,把上述紧凑型的字符串重新解析reparsed
3. 利用toprettyxml的方法,返回出漂亮的xml
from xml.etree import ElementTree as ET from xml.dom import minidom def prettify(root): """ 将节点转换成字符串,并添加缩进。 :param root: :return: """ rough_string = ET.tostring(root, encoding='utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent="\t") root = ET.Element("Family", {"age": "20"}) tree = ET.ElementTree(root) son1 = root.makeelement("Family", {"age": "18"}) son2 = root.makeelement("Family", {"age": "19"}) root.append(son1) root.append(son2) grandson = ET.SubElement(son1, "family", {"sex": "feman"}) grandson.text = "这是一个孙子" new_str = prettify(root) f = open("pretty.xml",'w',encoding='utf-8') f.write(new_str) f.close() # tree.write("pretty.xml", xml_declaration=True, short_empty_elements=True, encoding='utf-8')