Python xml.etree.ElementTree解析强制编码

vlk*_*vlk 2 python xml encoding xml.etree

我收到许多 XML 文件,其中一些文件的编码错误(例如,在 xml 标头中是 ISO-8859-1,但所有字符串都是 UTF-8,等等)

使用 xml.etree.ElementTree 进行解析,这也会读取带有编码的 xml 标头(有时是错误的)

input_element = xml.etree.ElementTree.parse("input.xml").getroot()
Run Code Online (Sandbox Code Playgroud)

我想强制使用另一种编码并从标头中忽略它。

有什么简单的方法可以做到这一点吗?

Tom*_*lak 6

如果您确定编码,则可以使用open()将文件读入字符串,然后使用ElementTree.fromstring()将该字符串转换为 XML 文档。

with open("input.xml", encoding="Windows-1252") as fp:
    xml_string = fp.read()
    tree = ElementTree.fromstring(xml_string)
Run Code Online (Sandbox Code Playgroud)

这将忽略 XML 声明,因为文件已经被解码(尽管是手动解码)。对于普通/兼容的 XML 文档,不建议使用此方法,而应使用此方法ElementTree.parse('filename')