ElementTree - Howto access text within XML tag element...

Diez B. Roggisch deets at nospam.web.de
Tue Aug 11 17:42:42 EDT 2009


cmalmqui schrieb:
> On Aug 11, 9:51 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>> cmalmqui schrieb:
>>> Hi,
>>> I am writing on a small XML parser and are currently stuck as I am not
>>> able to get the whole element name in ElementTree.
>>> Please see the below example where "print root[0][0]" returns
>>> "<Element 'Activity' at 018A3938>"
>>> Is there a way to get hold of the "Running" string in the tag using
>>> elementTree?
>>> <Activities>
>>>     <Activity Sport="Running">
>>>       <Id>2009-07-10T14:48:00Z</Id>
>>>       <Lap StartTime="2009-07-10T14:48:00Z">
>>>       .........
>>> For those of you that know how to program XML I have another
>>> question:
>>> I am currently "hardcoding" my XML parser using brackets, is this a
>>> good approach or should I build it using a "search on tag" approach.
>> What do you mean by that - hardcoding by brackets?
>>
>> Diez
> 
> Indeed, my current approach has been to hardcode the XML parser using
> brackets. Is there a more elegant way?
> 
> I am parsing a garmin xml file from a handheld GPS and as you can see
> in the below script, I am hardcoding each node:

As you don't give an actual example of how the XML looks like, it's hard 
to tell. But under the assumption that the tag-names are not generic, 
I'd certainly go for

   root.find("tagname")

instead. That's much clearer, and you don't rely on an actual order of 
elements.

Diez



More information about the Python-list mailing list