[Tutor] Using xml.etree

lists lists at justuber.com
Sat Sep 17 13:08:36 CEST 2011


Hi Tutors,

I have been trying to learn how to parse XML with Python and learn how
to use xml.etree. Lots of the tutorials seem to be very long winded.

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?

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']


More information about the Tutor mailing list