Add " encoding="utf-8"?> to xml file

Viewed 1106

I am creating an xml file, I just want that it should say this on the top

<?xml version="1.0" encoding="utf-8"?>

For now it says only

<?xml version="1.0" ?>

This is how I am creating it.

xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="   ")
with open("Test.xml", "w", encoding='utf-8') as f:
    f.write(xmlstr)
2 Answers

It is enough to add encoding parameter:

xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="   ", encoding="utf-8")

change "w" in the file save to "wb".

And, as suggested in the comments, to drop spurious parsing back to XML:

from lxml import etree

xml_object = etree.tostring(root,
                            pretty_print=True,
                            xml_declaration=True,
                            encoding='UTF-8')

Then it is enough to write xml_object to the file.

By adding the encoding argument you will get a byte string (that is why you have to change a file writing argument to binary mode). To return a string as you originally wanted and in the same time getting <?xml version="1.0" encoding="utf-8"?>, you may use the following code:

xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="   ", encoding="utf-8").decode("utf-8")
Related