【问题标题】:ElementTree cannot find elementElementTree 找不到元素
【发布时间】:2016-07-12 14:09:16
【问题描述】:

我有一个 XML 文档,我在下面的复制器中包含了足够的子集,tree.find() 没有返回任何结果:

import xml.etree.ElementTree as ET

xml_str = '''
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
   <System/>
</Event>
'''

tree = ET.fromstring(xml_str)
system = tree.find('System')              

我希望system 现在持有&lt;System&gt; 标签,但它是None。我在这里遗漏了什么吗?

当我使用数组索引(如 tree[0][0])时,它确实有效。

【问题讨论】:

  • 这不是System 标签,而是{http://schemas.microsoft.com/win/2004/08/events/event}System 标签。命名空间很重要。
  • ...编辑了复制器以使其完全复制/粘贴友好(以前,需要在解析之前修复文档,因此无法验证)。

标签: python elementtree


【解决方案1】:

在搜索中使用命名空间:

>>> doc.find('{http://schemas.microsoft.com/win/2004/08/events/event}System')
<Element {http://schemas.microsoft.com/win/2004/08/events/event}System at 0x10167e5a8>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多