[Tutor] XML and ElementTree
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Apr 25 20:05:38 EDT 2016
On 25/04/16 17:24, Marco Soldavini wrote:
> 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
Answer: The ones that suit what you want to do with it.
But you haven't told us what you plan on using it for so
we can't tell you what is suitable.
> <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
So you could have a list or a dictionary of Stations.
Each station might be simple values, or tuples, or dictionaries
or an instance of a Station class.
> I could append all data in a long list, but is this good?
It all depends on what you want to do.
If you just want to process all the stations sequentially then yes,
a long list is good. (Unless its too long in which case you may
be better with a database or a flat file.)
> 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']....
That suggests a dictionary or class would be best. (Although
a named tuple or database may also be appropriate.)
> But what if I have more than one structure like station which has the same keys?
Figuring out object identity is always tricky when the data
is similar. a Database solution offers row ids to disambiguate similar
entries. A class based solution has an id (usually the memory address),
a list has its index. Its really up to you to determine the best
option based on your needs.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list