【问题标题】:lxml.objectify.parse fails while fromstring workslxml.objectify.parse 在 fromstring 工作时失败
【发布时间】:2016-03-29 19:56:19
【问题描述】:

当我使用文件 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' 对象没有属性 'tag'

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

print(root.tag)

【问题讨论】:

    标签: python python-3.x io lxml.objectify


    【解决方案1】:

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

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

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

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

    在这种情况下使用getroot() 到达根元素:

    tree = objectify.parse(f)
    root = tree.getroot()
    

    【讨论】:

    • 谢谢。在任何文档中都没有看到这个......这修复了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多