lxml objectify - attribute elements to list.

Kev Dwyer kevin.p.dwyer at gmail.com
Sun Feb 8 07:46:08 EST 2015


Sayth Renshaw wrote:

> 
> Hi
> 
> How can I actually access the values of an element with lxml objectify?
> 
> for example if I had this element in my xml file.
> 
> <Track VenueName="Flemington" VenueDesc="Flemington" VenueAbbr="FLEM"
> VenueCode="151" TrackName="Main" TrackCode="149">
> 
> I can see all the attributes using this.
> 
> In [86]: for child in root.getchildren():
>     print(child.attrib)
>    ....:
> {}
> {'RequestCode': '', 'RequestId': '0'}
> {}
> {}
> ...
> {}
> {}
> {}
> {'Category': 'Metro', 'AbrClubDesc': 'VRC', 'State': 'VIC', 'ClubCode':
> {'10018', 'Title': 'Victoria Racing Club'} 'TrackName': 'Main',
> {'VenueName': 'Flemington', 'TrackCode': '149', 'VenueAbbr': 'FLEM',
> {'VenueDesc': 'Flemington', 'VenueCode': '151'} } }
> ...
> 
> Trying to access by attribs isn't working or me.
> 
> In [90]: names = [p.text for p in root.Track.attrib['VenueName']]
> 
---------------------------------------------------------------------------
> AttributeError                            Traceback (most recent call
> last) <ipython-input-90-8e4bdae01d63> in <module>()
> ----> 1 names = [p.text for p in root.Track.attrib['VenueName']]
> 
> AttributeError: 'str' object has no attribute 'text'
> 
> 
> What am I missing with this?
> 
> Thanks
> 
> Sayth


Hello

Is this what you're trying to do?

(tmp-179b92275909243d)kev at pluto ~/virtual-envs/tmp-179b92275909243d  python                                                                                                               
Python 3.4.1 (default, May 23 2014, 17:48:28) [GCC] on linux                                                                                                                              
Type "help", "copyright", "credits" or "license" for more information.                                                                                                                    
>>> from lxml import objectify
>>> root = objectify.fromstring('<root><Track VenueName="Flemington" 
VenueDesc="Flemington" VenueAbbr="FLEM" VenueCode="151" TrackName="Main" 
TrackCode="149"/></root>')
>>> root.Track
''
>>> root
<Element root at 0x7f65c6965d08>
>>> for child in root.getchildren():
...     print(child.attrib)
... 
{'VenueCode': '151', 'TrackCode': '149', 'VenueName': 'Flemington', 
'VenueDesc': 'Flemington', 'TrackName': 'Main', 'VenueAbbr': 'FLEM'}
       
>>> for child in root.getchildren():
...     print(child.get('VenueName'))
... 
Flemington
>>> 

Cheers,

Kev





More information about the Python-list mailing list