【问题标题】:Python xml ElementTree findall returns empty resultPython xml ElementTree findall 返回空结果
【发布时间】:2016-11-08 08:49:29
【问题描述】:

我想使用 Python xml ElementTree API 解析以下 XML 文件。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foos>
  <foo_table>

    <!-- bar -->
    <fooelem>
      <fname>BBBB</fname>
      <group>SOMEGROUP</group>
      <module>some module</module>
    </fooelem>
  
    <fooelem>
      <fname>AAAA</fname>
      <group>other group</group>
      <module>other module</module>
    </fooelem>
    <!-- bar -->

  </foo_table>
</foos>

在此示例代码中,我尝试查找/foos/foo_table/fooelem/fname 下的所有元素,但显然findall 在运行此代码时没有找到任何内容。

import xml.etree.cElementTree as ET
tree = ET.ElementTree(file="min.xml")
for i in tree.findall("./foos/foo_table/fooelem/fname"): 
    print i

root = tree.getroot()
for i in root.findall("./foos/foo_table/fooelem/fname"): 
    print i

我没有使用 ElementTree API 的经验,但我使用了 https://docs.python.org/2/library/xml.etree.elementtree.html#example 下的示例。为什么它在我的情况下不起作用?

【问题讨论】:

    标签: python xml python-2.7


    【解决方案1】:

    foos 是你的root,你需要在下面开始findall,例如

    root = tree.getroot()
    for i in root.findall("foo_table/fooelem/fname"): 
        print i.text
    

    输出:

    BBBB
    AAAA
    

    【讨论】:

    • 谢谢。选择 root.findall() 而不是 tree.findall() 是否有特定的原因?似乎两者都显示相同的结果。
    • @ThoWe:我不知道为什么,我猜这只是惯例。
    【解决方案2】:

    这是因为您使用的路径在根元素 (foos) 之前开始。
    改用这个:foo_table/fooelem/fname

    【讨论】:

    • 比我快 8 秒。
    【解决方案3】:

    findall 不起作用,但这样做:

    e = xml.etree.ElementTree.parse(myfile3).getroot()
    mylist=list(e.iter('checksum'))
    print (len(mylist))
    

    mylist 将具有适当的长度。

    【讨论】:

    • 不鼓励仅使用代码的答案。请编辑您的答案并为您的代码添加一些解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多