将 XML 从 URL 解析为 python 对象 [英] Parse XML from URL into python object

查看:38
本文介绍了将 XML 从 URL 解析为 python 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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})

这篇关于将 XML 从 URL 解析为 python 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆