将 XML 从 URL 解析为 python 对象

2022-01-10 00:00:00 python django xml urllib2 xml-parsing

问题描述

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.


解决方案

我会使用 xmltodictXML 数据结构中创建一个 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})

相关文章