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

Ned Deily nad at acm.org
Tue Aug 11 09:13:07 CEST 2009


In article 
<1ad8dac1-8fff-493a-a197-d847e7b6a761 at c2g2000yqi.googlegroups.com>,
 cmalmqui <cmalmqui at gmail.com> wrote:
> 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">
>       .........

"Running" is the value of the "Sport" attribute of the "Activity" 
element.  The documentation for the Element interface lists several ways 
to access element attributes; in your example,

>>> elem = root[0][0]
>>> elem.get("Sport")
'Running'
>>> elem.attrib
{'Sport': 'Running'}
>>> elem.items()
[('Sport', 'Running')]

See http://docs.python.org/library/xml.etree.elementtree.html

-- 
 Ned Deily,
 nad at acm.org




More information about the Python-list mailing list