【问题标题】:Consuming XML restful service, outputting in JSON - for loop issue使用 XML RESTful 服务,以 JSON 格式输出 - for 循环问题
【发布时间】:2011-04-08 18:32:37
【问题描述】:

我在互联网上的另一台服务器上有一个 RESTful 服务。我正在发送一个请求,该请求返回一个带有一些属性的 XML 项。

我还有另一个使用本地存储的 XML 的 python 函数,当我向它提供参数时,它将遍历所有元素,并仅返回与该参数匹配的 XML 项,即 mysite/search/ 123. 我可以使用以下方法输出:

from xml.dom.minidom import parseString
import json
import urllib2
from django.http import HttpResponse
    def index(request, number="1"):
        #file = urllib2.urlopen('myfile.xml')
        file = open('myfile.xml','r')
        data = file.read()
        dom = parseString(data)
        rows = dom.getElementsByTagName("root")[0].getElementsByTagName("subroot")[0].getElementsByTagName("theData")
        for row in rows:
            return  HttpResponse(json.dumps({'name':row.getAttribute("name"),'address': row.getAttribute("address"), 'phone': row.getAttribute("phone")}, sort_keys=True, indent=4))

注意我如何在 for 循环中使用 row,然后使用 row.getAttribute() 访问属性。如果我只有 1 个 XML 项,则无需循环,因此无需迭代,因此无需使用 row 对象来使用 getAttribute() 方法。

我只想检索这一条数据。有人可以帮忙吗?

PS,如果我尝试对单个 XML 数据执行循环,我会收到一条错误消息: TypeError: Iteration over a non-sequence.

【问题讨论】:

    标签: python xml json rest


    【解决方案1】:

    您需要将生成器作为响应传递给 Django:

    response_generator = (
        json.dumps(
            {
                'name': row.getAttribute("name"),
                'address': row.getAttribute("address"),
                'phone': row.getAttribute("phone")},
            sort_keys=True,
            indent=4)
        for row in rows)
    
    return HttpResponse(response_generator)
    

    另请参阅:http://docs.djangoproject.com/en/dev/ref/request-response/#passing-iterators

    希望对你有帮助。

    【讨论】:

    • 哇,非常感谢!!现在完美运行!实际上,我还有另一个问题,我认为不需要打开另一个线程,但也许有人可以提供帮助。在我的 urls.py 中,我有 (r'^names/(\d{1,2})$','foo.views.index'),,它接受一个数字(例如 mysite/names/12)并为此显示 XML,但是我如何表达正则表达式以便我可以采用字符串而不是整数?例如 mysite/names/john ?谢谢
    • 请参阅 re 包文档中的正则表达式手册。上述解决方案:(r'^names/(\w+)$','foo.views.index');也不要忘记删除到 int 的转换。
    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    相关资源
    最近更新 更多