1

当我使用文件 IO 而不是字符串 IO 时,为什么 lxml.objectify.parse 会失败?

以下代码有效:

with open(logPath,'r', encoding='utf-8') as f:
    xml = f.read()
    root = objectify.fromstring(xml)

print(root.tag)

以下代码失败并出现错误:

AttributeError:“lxml.etree._ElementTree”对象没有属性“标签”

with open(pelogPath,'r', encoding='utf-8') as f:
    #xml = f.read()
    root = objectify.parse(f)

print(root.tag)
4

1 回答 1

1

那是因为fromstring()会直接返回一个根元素:

从字符串中解析 XML 文档或片段。返回根节点(或解析器目标返回的结果)。

parse()将返回一个ElementTree对象:

返回一个加载了源元素的 ElementTree 对象。

在这种情况下用于getroot()获取根元素:

tree = objectify.parse(f)
root = tree.getroot()
于 2016-03-29T20:01:34.703 回答