在 python 2.54 上添加 xml 元标记

Add xml metatag on python 2.54

我正在编写使用对象 xml.etree.ElementTree 的 python 2.54 脚本。我正在使用函数 write 将结果 xml 写入文件。问题是,我需要一个 XML 元标记:<?xml version="1.0" encoding="UTF-8"?>,并且如此处所述: https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write

所有需要做的就是在 write 的第二个参数上传递 true。但这似乎只适用于 python 2.6 及更高版本。

关于如何在 python 2.5.4 上完成的任何想法(如果可能,那就是......)

似乎强制编写 xml 声明的最简单方法是传递与 us-asciiutf-8 不同的编码。这并没有真正记录下来,但快速浏览一下 source for the write() method 就会发现:

def write(self, file, encoding="us-ascii"):
    assert self._root is not None
    if not hasattr(file, "write"):
        file = open(file, "wb")
    if not encoding:
        encoding = "us-ascii"
    elif encoding != "utf-8" and encoding != "us-ascii":
        file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
    self._write(file, self._root, encoding, {})

比较区分大小写,因此如果您使用 encoding="UTF-8"(而不是 encoding="utf-8"),您最终会得到您想要的结果。