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='\t')
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>

相关文章:

  • 2022-01-22
  • 2022-01-06
  • 2021-08-23
  • 2021-09-09
  • 2021-07-23
  • 2022-02-27
  • 2022-01-30
  • 2022-12-23
猜你喜欢
  • 2021-10-15
  • 2022-12-23
  • 2021-11-11
  • 2021-05-20
  • 2022-12-23
  • 2021-12-01
相关资源
相似解决方案