ThoWe
ThoWe

Reputation: 346

Python xml ElementTree findall returns empty 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?

Upvotes: 1

Views: 4983

Answers (3)

Nick Iac
Nick Iac

Reputation: 1

findall doesn't work, but this does:

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

mylist will have the proper length.

Upvotes: 0

Maximilian Peters
Maximilian Peters

Reputation: 31649

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

Upvotes: 2

Olian04
Olian04

Reputation: 6862

This is because the path you are using begins BEFORE the root element (foos).
Use this instead: foo_table/fooelem/fname

Upvotes: 1

Related Questions