python: xml.etree.elementtree.ElemenTtree.write() declaration tag

I had the same problem, looked in the code of the ElementTree.py and saw the following.

For the root tag (single quotes):

        if method == "xml":
            write("<?xml version='1.0' encoding='%s'?>\n" % encoding)

And for the attributes (double quotes):

write(" %s=\"%s\"" % (qnames[k], v))

It's hardcoded that way...

I changed it (locally) to:

"<?xml version=\"1.0\" encoding=\"%s\"?>\n"

So every attribute is double quoted now.


I did the same as bg1987. Here is the function I wrote in case is useful to somebody

def wrTmp(treeObject, filepath):
    xml_str = ('<?xml version="1.0" encoding="UTF-8"?>' + '\n' + xml.etree.ElementTree.tostring(treeObject.getroot(), method='xml'))
    with open(filepath, 'wb') as xml_file:
         xml_file.write(xml_str)

Eventually I used the tostring function and appended the XML to the correct tag and then the python file.write function. It's ugly (and im lying about the actual encoding of the file) but it works.

Tags:

Python

Xml