2016-11-08 158 views
0

我想使用Python xml ElementTree API解析以下XML文件。Python xml ElementTree findall返回空结果

<?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下使用的例子。为什么它不适用于我的情况?

回答

0

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

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

输出:

BBBB 
AAAA 
+0

谢谢。是否有特定的理由来选择root.findall()而不是tree.findall()?看起来两者都显示了相同的结果。 – ThoWe

+0

@ThoWe:我没有理由知道,我的猜测是这只是惯例。 –

1

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

+0

殴打我8秒。 –

+0

@MaximilianPeters hehe,谢谢。赞赏:) – Olian04

0

findall不起作用,但这:

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

MYLIST将有适当的长度。

+0

不提供代码解答。请编辑您的答案并为您的代码添加一些解释。 – WebDevBooster