ThoWe ThoWe - 26 days ago 8
Python Question

Python xml ElementTree findall returns emtpy result

I would like to parse following XML file using the Python xml ElementTree API.

<?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>


In this example code I try to find all the elements under /foos/foo_table/fooelem/fname but obviously findall doesn't find anything when running this code.

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


I am not experienced with the ElementTree API, but I've used the example under https://docs.python.org/2/library/xml.etree.elementtree.html#example. Why is it not working in my case?

Answer

foos is your root, you would need to start findall below, e.g.

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

Output:

BBBB
AAAA
Comments