[Tutor] XML and ElementTree

Marco Soldavini magyar1886 at gmail.com
Mon Apr 25 12:24:46 EDT 2016


I've a few questions about parsing XML. I wrote some code that works
but I want to know which are the most intelligent data structures to
parse data to

Consider that my XML file is something like the following:


<Settings>
<Station>
    <Id>1</Id>
    <Data1>XXX</Data1>
    <Groups>
       <Group>
       ....
       </Group>
       <Group>
       ....
       </Group>
    </Groups>
</Station>
<Station>
....
</Station>
</Settings>

So root element can have station child element from 1 to n
Each station element have unique child elements apart from groups
which may have more group child element each with a few tags

Now I want to parse this xml file and get the tag values into
variables in python
I could have 1 station element or 2 or 3
I could append all data in a long list, but is this good?
Could it be better to build a dictionary for each station element and
then build a list of dictionary
Which method you suggest to find data and use it after parsing it?

If later in the program I want to access a variable value I want to do
it with the xml tag name and not with an index like Settings[10] for
example but something like Settings['tag']....

But what if I have more than one structure like station which has the same keys?

Following is part of my code for now.
Thanks!
marco


try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


# Settings XML File Parsing

tree = ET.parse('settingstest.xml')
root = tree.getroot()

stations = len(root)
print "Found ",stations, " stations configured in settings file"

Settings = []
for station in root:
   StationId = station.find('StationId')
   Settings.append(StationId)
   .....


More information about the Tutor mailing list