rahul  Kushwaha
rahul Kushwaha

Reputation: 2819

toprettyxml() not working while writing back to xml file

I used python to modify the XML file and want to write the changes in XML back to the file in the pretty form, I am using this code to write I am using from xml.dom.minidom import parse, parseString

dom1 = parse("./test.xml")

f.write(dom1.toprettyxml(indent="\t", newl="\n", encoding="utf-8"))

after executing this code it's adding multiple new lines, I think it's adding new line after the new line already present in the XML as the file was already formatted before reading

how to write XML in pretty from python?

Upvotes: 0

Views: 1169

Answers (1)

CC7052
CC7052

Reputation: 577

You can use 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'))

Upvotes: 1

Related Questions