Parse XML from URL into python object Parse XML from URL into python object python python

Parse XML from URL into python object


I'd use xmltodict to make a python dictionary out of the XML data structure and pass this dictionary to the template inside the context:

import urllib2import xmltodictdef homepage(request):    file = urllib2.urlopen('https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread')    data = file.read()    file.close()    data = xmltodict.parse(data)    return render_to_response('my_template.html', {'data': data})


xmltodict using urllib3

import tracebackimport urllib3import xmltodictdef getxml():    url = "https://yoursite/your.xml"    http = urllib3.PoolManager()    response = http.request('GET', url)    try:        data = xmltodict.parse(response.data)    except:        print("Failed to parse xml from response (%s)" % traceback.format_exc())    return data


xmltodict using requests

import requestsimport xmltodicturl = "https://yoursite/your.xml"response = requests.get(url)data = xmltodict.parse(response.content)