lxml objectify - attribute elements to list.

Stefan Behnel stefan_ml at behnel.de
Sun Feb 8 14:29:42 EST 2015


Sayth Renshaw schrieb am 08.02.2015 um 12:22:
> 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'

As you can see from the output above, "attrib" is a mapping from strings
(attribute names) to strings (attribute values). So just use

    name = root.Track.attrib['VenueName']

or, even simpler:

    name = root.Track.get('VenueName')

Stefan





More information about the Python-list mailing list