parsing XML

Adam Tauno Williams awilliam at whitemice.org
Fri May 14 16:44:48 EDT 2010


On Fri, 2010-05-14 at 22:17 +0200, Stefan Behnel wrote:
> >> <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> 

from lxml import etree
handle = open('file', 'rb')
doc = etree.parse(handle)
handle.close()
players = [ ]
for player in doc.xpath('/team/player'):
  players.append({ 'name': player.xpath('./@name')[0],
                   'age': player.xpath('./@age')[0],
                   'height': player.xpath('./@height')[0] } )
print players
-- 
Adam Tauno Williams <awilliam at whitemice.org> LPIC-1, Novell CLA
<http://www.whitemiceconsulting.com>
OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba




More information about the Python-list mailing list