Python xml.eTree.ElementTree module generates xml file indentation problem?

I think this module is good for building xml documents, but there is a problem with writing it as a file. 1 is missing the xml header declaration, 2 is not indented. For example, the minidom module is generated very well. How can you solve this problem? I"d like to be more specific.

Mar.21,2021

is not indented, just indent it before writing to the file.
does not have a xml header, just add a line before writing to the file.


xml header declaration is supported, and
xml.write ("your_file.xml", xml_declaration=True, encoding= "utf-8", method= "xml")
can be generated by writing.


I have solved this problem. It is first converted to string, and then outputted into xml documents using the minidom module. For example:

    xml_string = ET.tostring(Rp)
    xml_write = DOM.parseString(xml_string)
    with open(output_path, 'w') as handle:
        xml_write.writexml(handle, indent='  ', newl='\n', encoding='utf-8')

where Rp is the xml I built.

Menu