我使用python修改了XML文件,并希望将XML的更改以漂亮的形式写回到文件中,我正在使用此代码编写我正在使用from xml.dom.minidom import parse, parseString
dom1 = parse("./test.xml")
f.write(dom1.toprettyxml(indent="\t", newl="\n", encoding="utf-8"))
执行此代码后,它会添加多行新行,我认为这是在XML中已经存在的新行后添加新行,因为文件已在读取之前进行了格式化
如何用python漂亮地编写XML?
您可以使用minidom
:
import xml.etree.cElementTree as ET
import xml.dom.minidom
xmlstr = xml.dom.minidom.parseString(ET.tostring(dom1)).toprettyxml(indent=" ")
with open("pretty.xml", "bw") as f:
f.write(xmlstr.encode('utf-8'))