Anybody using xml.etree?

I asked this question over at the Python tutors group but it seems
that few people there had experience of it.

I'm trying to access a UK postcode API at www.uk-postcodes.com to take
a UK postcode and return the lat/lng of the postcode. This is what the
XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml

The function below returns a dict with the xml tag as a key and the
text as a value. Is this a correct way to use xml.etree? Is there a
better way of doing this?

Thanks in advance!

Chris


def ukpostcodesapi(postcode):
       import urllib
       import xml.etree.ElementTree as etree

       baseURL='http://www.uk-postcodes.com/'
       geocodeRequest='postcode/'+postcode+'.xml'

       #grab the xml
       tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest))
       root=tree.getroot()
       results={}
       for child in root[1]: #here's the geo tag
               results.update({child.tag:child.text}) #build a dict
containing the geocode data
       return results

#example usage (testing the function)
results = ukpostcodesapi('hu11aa')
print results['lat']+' '+results['lng']

Reply via email to