I'm trying to parse an xml file using Python through root.findall
.
Basically my file looks like this - and I'm trying to access elements under "Level3".
Edit: @trincot, already provided solution.....but, Now, I've added namespace to the sample data(xmlns="http://xyz.abc/forms"), which is causing the trouble. Why would adding 'xmlns=' cause the issue ? :O
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xyz.abc/forms" xmlns:abc="http://bus-message-envelope" xmlns:env="http://www.w3.org/2003/05/soap-envelope" abc:version="1-2">
<env:Header>
<abc:col1>col1Text</abc:col1>
<abc:col2>col2Text</abc:col2>
<abc:col3>col3Text</abc:col3>
</env:Header>
<env:Body>
<Level1>
<Level2 schemaVersion="1-1">
<Level3>
<cell1>cell1Text</cell1>
<cell2>cell2Text</cell2>
<cell3>cell3Text</cell3>
<cell4>cell4Text</cell4>
</Level3>
</Level2>
</Level1>
</env:Body>
</env:Envelope>
Trying this, but doesn't return anything :
from xml.etree import ElementTree
tree = ElementTree.parse("/tmp/test.xml")
root = tree.getroot()
for form in root.findall(".//Level3"):
print(form.text)
print("Inside Loop") --> Not even hitting this
Expected Output:
cell1Text
cell2Text
cell3Text
cell4Text
I was able to access the same elements through code below. But, how to achieve this using findall
?
for x in root[1][0][0][0]:
print(x.text)
Output:
cell1Text
cell2Text
cell3Text
cell4Text
I did go through most of Stack Overflow, but couldn't get an answer to this. Tried many things but failed :( .