使用ElementTree将XML版本从1.0更改为1.1?

时间:2018-07-24 16:45:25

标签: xml python-2.7 jenkins elementtree xml-1.1

我正在使用元素树库修改xml文件,然后将元素树转换回xml。
在此过程中,xml版本会更改(1.1-> 1.0)。
但是,由于这个有缺陷的xml文件,我无法对Jenkins作业执行必要的rest调用。

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

对元素树进行一些操作。现在转换回xml文件

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

这是原始配置文件与已编辑文件之间的区别

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

1 个答案:

答案 0 :(得分:0)

该版本是硬编码的,因此请构建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)