将URL中的XML解析为python对象 [英] Parse XML from URL into python object
问题描述
goodreads网站具有此API,用于访问用户的货架: https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread
The goodreads website has this API for accessing a user's 'shelves:' https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread
它返回XML。我正在尝试创建一个Django项目,该项目通过此API在书架上显示书籍。我正在寻找一种方法(或者是否有比该方法更好的方法)来编写我的视图,以便可以将一个对象传递给模板。当前,这是我正在做的事情:
It returns XML. I'm trying to create a django project that shows books on a shelf from this API. I'm looking to find out how (or if there is a better way than) to write my view so I can pass an object to my template. Currently, this is what I'm doing:
import urllib2
def homepage(request):
file = urllib2.urlopen('https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread')
data = file.read()
file.close()
dom = parseString(data)
如果我正确地执行此操作,我不完全确定如何操作该对象。我正在关注教程。
I'm not entirely sure how to manipulate this object if I'm doing this correctly. I'm following this tutorial.
推荐答案
我将使用 xmltodict
从 XML
数据结构中制作一个python字典,并将该字典传递到上下文中的模板:
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 urllib2
import xmltodict
def 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})
这篇关于将URL中的XML解析为python对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!