Skip to content Skip to sidebar Skip to footer

Python: Xml.etree.elementtree.elementtree.write() Declaration Tag

I’ve created an XML document using xml.etree.elementtree.Element, and wanted to print it using the ElementTree.write() function but the declaration tag that comes out is

Solution 1:

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.

Solution 2:

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.

Solution 3:

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)

Solution 4:

I had to do pretty much the same thing, except the other way around, due to hacks in various $workplace tools that demand single quotes where python's ElementTree.write puts in double quotes. (A bit of code looks for the literal string status='ok' and does not recognize status="ok". Yes, that code is broken—in several ways, actually—but I just have to work around it.)

Fortunately "user data" single or double quotes are encoded as &apos; and &quot; (respectively). In my case I was already using tostring rather than write (for other reasons), so I have:

import xml.etree.ElementTree as ET
# [... mass snippage]
        text = ET.tostring(reply).replace('"', "'")
        # [... snippaage]
        self.wfile.write(text)

(Obviously you'll want replace("'", '"') instead.)

Solution 5:

Another way would be (if you also want to pretty print your xml) to use the minidom.toprettyxml(encoding="UTF-8") which puts the xml and encoding declaration in double quotes:

from xml.dom import minidom
xmlDom = minidom.parse("my_file.xml")

prettyXML = xmlDom.toprettyxml(encoding="UTF-8")

myfile = open(fileName, mode="wb")
myfile.write(prettyXML)
myfile.close()

Post a Comment for "Python: Xml.etree.elementtree.elementtree.write() Declaration Tag"