Change XML Version from 1.0 to 1.1 with ElementTree?

2.1k Views Asked by At

I'm using the Element tree library to modify an xml file and then convert the element tree back to xml.
In the process of doing so the xml version changes (1.1 -> 1.0).
However, I cannot perform my necessary rest calls to the Jenkins job because of this flawed xml file.

config_xml = server.get_job_config("Automation Enhancement Template")
root = xml.etree.ElementTree.fromstring(config_xml)

do some manipulation on element tree. Now convert back to xml file

xmlstr = ET.tostring(tree._root, encoding="UTF-8", method='xml')

Here is the difference between the original config file vs the edited

<?xml version='1.1' encoding='UTF-8'?>
<?xml version='1.0' encoding='UTF-8'?>
1

There are 1 best solutions below

0
On

The version is hard coded, so build a custom fork of ElementTree\SimpleXMLWriter.py py-elementtree/elementtree/SimpleXMLWriter.py

class XMLWriter:

def __init__(self, file, encoding="us-ascii"):
    if not hasattr(file, "write"):
        file = open(file, "w")
    self.__write = file.write
    if hasattr(file, "flush"):
        self.flush = file.flush
    self.__open = 0 # true if start tag is open
    self.__tags = []
    self.__data = []
    self.__encoding = encoding

def __flush(self):
    # flush internal buffers
    if self.__open:
        self.__write(">")
        self.__open = 0
    if self.__data:
        data = string.join(self.__data, "")
        self.__write(escape_cdata(data, self.__encoding))
        self.__data = []

##
# Writes an XML declaration.

def declaration(self):
    encoding = self.__encoding
    if encoding == "us-ascii" or encoding == "utf-8":
        self.__write("<?xml version='1.0'?>\n")
    else:
        self.__write("<?xml version='1.0' encoding='%s'?>\n" % encoding)