2016-11-08 69 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