Reputation: 319
I have the following XML file that I'm trying to iterate through using xml.etree:
<safetypadapiresponse><url></url><refcode /><status>SUCCESS</status><message><pcrs>
<pcr>
<eCase01m>1234</eCase01m>
<eProcedures03>12 Lead ECG Obtained</eProcedures03>
<eMedications03>Oxygen</eMedications03>
</pcr>
</pcrs></message></safetypadapiresponse>
I'm unable to find any of the child elements after 'message' with the following:
import xml.etree.ElementTree as ET
tree = ET.parse(xmlFile)
root = tree.getroot()
for member in root.findall('pcr'):
print(member)
The following child elements are listed when the following is run:
for member in root:
print(member)
I'm trying to retrieve all the information under the pcr element (i.e. eCase01m, eProcedures03, eMedications03).
Upvotes: 2
Views: 5450
Reputation: 24930
For the sake of completeness, let me add that you can also try xpath:
for i in tree.xpath('*//pcr/*'):
print(i.tag)
Output:
eCase01m
eProcedures03
eMedications03
Upvotes: 1
Reputation: 3328
You can use findall()
in two ways. Unhelpfully this is mentioned in two different parts of the docs:
Element.findall() finds only elements with a tag which are direct children of the current element.
...
Finds all matching subelements, by tag name or path. Returns a list containing all matching elements in document order.
What this means is if you look for a tag, you are only searching the direct children of the current element.
You can use XPath instead to look for the parts you are interested in, which will recurse through the docs looking for matches. Either of the following should do:
root.findall('./message/pcrs/pcr') # Find them relative to this node
root.findall('.//pcr') # Find them anywhere below the current node
Upvotes: 4