Home > OS >  Use python 3 to parse XML child element
Use python 3 to parse XML child element

Time:04-05

I have an XML file like below:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <geoEventDefinition guid="3ab37e92-825c-4fdf-afa6-7b7536999ccd">
     <fieldDefinitions>
         <fieldDefinition name="id" type="String" cardinality="One">
             <fieldDefinitionTag>
                 <name>TRACK_ID</name>
             </fieldDefinitionTag>
             <fieldDefinitions/>
         </fieldDefinition>
         <fieldDefinition name="position" type="Group" cardinality="One">
             <fieldDefinitions>
                 <fieldDefinition name="longitude" type="Double" cardinality="One">
                     <fieldDefinitions/>
                 </fieldDefinition>
                 <fieldDefinition name="latitude" type="Double" cardinality="One">
                     <fieldDefinitions/>
                 </fieldDefinition>
             </fieldDefinitions>
         </fieldDefinition>
     </fieldDefinitions> </geoEventDefinition>

I'm iterating through the file to retrieve the fieldDefinition attributes (i.e. {'name': 'id', 'type': 'String', 'cardinality': 'One'}) using the below:

from xml.etree import ElementTree as ET
tree = ET.parse(xmlFile)
root = tree.getroot()

for child in root.iter('fieldDefinition'):
    print(child.attrib)

I also need to return the name tag data (i.e. TRACK_ID) under the fieldDefinitionTag if it exists, but cannot figure out how to do so.

Any help is appreciated.

CodePudding user response:

You can use

import xml.etree.ElementTree as ET    
tree = ET.parse('xmlFile')
root = tree.getroot()
for child in root.iter("fieldDefinition"):
    print(child.attrib)
    for n in child.iter("name"):
        print(n.text)

Its output is

{'cardinality': 'One', 'type': 'String', 'name': 'id'}
TRACK_ID
{'cardinality': 'One', 'type': 'Group', 'name': 'position'}
{'cardinality': 'One', 'type': 'Double', 'name': 'longitude'}
{'cardinality': 'One', 'type': 'Double', 'name': 'latitude'}

So it outputs the attributes of all fieldDefinitions.

  • Related