1 from xml.etree import ElementTree as ET 2 from xml.dom import minidom 3 4 root = ET.Element('root',{'age':'18'}) 5 6 son=ET.SubElement(root,'root',{'age':'18'}) 7 ET.SubElement(son,'haha',{'bb':'fhfhf'}) 8 9 # tree = ET.ElementTree(root) 10 # tree.write('aha.xml') 11 12 def mywrite(root,file_path): 13 rough_str = ET.tostring(root,'utf-8') 14 reparsed = minidom.parseString(rough_str) 15 new_str = reparsed.toprettyxml(indent=' ') 16 f = open(file_path,'w',encoding='utf-8') 17 f.write(new_str) 18 f.close() 19 20 mywrite(root,'nnnn.xml')
结果
<?xml version="1.0" ?>
<root age="18">
<root age="18">
<haha bb="fhfhf"/>
</root>
</root>