我想使用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下使用的例子。为什么它不适用于我的情况?
谢谢。是否有特定的理由来选择root.findall()而不是tree.findall()?看起来两者都显示了相同的结果。 – ThoWe
@ThoWe:我没有理由知道,我的猜测是这只是惯例。 –