导入开头带有编码器元素的 xml 文件(使用 lxml)

Importing xml files with an encoder element at the start(using lxml)

我有一个文件 trace.xml。该文件的第一行是 <?xml version="1.0" encoding="UTF-8"?>。我尝试使用以下命令读取数据:

with open('trace.xml') as fobj:
xml=fobj.read()
root = etree.fromstring(xml)

然而,这会产生以下错误:ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration. 我假设它是因为我提到的第一个标签 above.Is 有解决这个问题的方法,我们将不胜感激。

尝试改变

root = etree.fromstring(xml)

root = etree.fromstring(xml.encode())

看看它是否有效。