parsing XML
superpollo
utente at esempio.net
Sat May 15 12:25:05 EDT 2010
superpollo ha scritto:
> kaklis at gmail.com ha scritto:
>> Hi to all, let's say we have the following Xml
>> <team>
>> <player name='Mick Fowler' age='27' height='1.96m'>
>> <points>17.1</points>
>> <rebounds>6.4</rebounds>
>> </player>
>> <player name='Ivan Ivanovic' age='29' height='2.04m'>
>> <points>15.5</points>
>> <rebounds>7.8</rebounds>
>> </player>
>> </team>
>>
>> How can i get the players name, age and height?
>> DOM or SAX and how
>>
>> Thanks
>> Antonis
>
> another minimal xml.etree.ElementTree solution:
>
> >>> print document
> <team>
> <player name='Mick Fowler' age='27' height='1.96m'>
> <points>17.1</points>
> <rebounds>6.4</rebounds>
> </player>
> <player name='Ivan Ivanovic' age='29' height='2.04m'>
> <points>15.5</points>
> <rebounds>7.8</rebounds>
> </player>
> </team>
> >>> import xml.etree.ElementTree as ET
> >>> team = ET.XML(document)
> >>> for player in team:
> ... print player.attrib["name"]
> ... print player.attrib["age"]
> ... print player.attrib["height"]
> ... print
> ...
> Mick Fowler
> 27
> 1.96m
>
> Ivan Ivanovic
> 29
> 2.04m
>
> >>>
>
> bye
or, an alternative xml.dom.minidom solution:
>>> import xml.dom.minidom as MD
>>> team = MD.parseString(document)
>>> players = team.getElementsByTagName("player")
>>> for player in players:
... print player.getAttribute("name")
... print player.getAttribute("age")
... print player.getAttribute("height")
... print
...
Mick Fowler
27
1.96m
Ivan Ivanovic
29
2.04m
>>>
bye
More information about the Python-list
mailing list