toprettyxml()在写回xml文件时不起作用

问题描述 投票:0回答:1

我使用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?

python xml minidom
1个回答
0
投票

您可以使用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'))
© www.soinside.com 2019 - 2024. All rights reserved.