from xml.etree import ElementTree as ET
from xml.dom import minidom root = ET.Element('root',{'age':''}) son=ET.SubElement(root,'root',{'age':''})
ET.SubElement(son,'haha',{'bb':'fhfhf'}) # tree = ET.ElementTree(root)
# tree.write('aha.xml') def mywrite(root,file_path):
rough_str = ET.tostring(root,'utf-8')
reparsed = minidom.parseString(rough_str)
new_str = reparsed.toprettyxml(indent='\t')
f = open(file_path,'w',encoding='utf-8')
f.write(new_str)
f.close() mywrite(root,'nnnn.xml')
结果
<?xml version="1.0" ?>
<root age="18">
<root age="18">
<haha bb="fhfhf"/>
</root>
</root>