The*_*eve 1 python django lxml django-views
嘿大家,过去几天我在试图解决我的问题时得到了一些惊人的帮助.我只有最后一个问题(我希望):)
我试图从我的xml中获取最后一个元素并将其放在一个变量中.我正在使用django,python和lxml库.
我想要做的是,浏览我从API调用中获得的XML,找到最新的项目(它将具有最大的ID号),然后将其分配给存储在我的数据库中的变量.我在找到如何找到最新,最新的元素时遇到了一些麻烦.
这是一段代码:
req2 = urllib2.Request("http://web_url/public/api.php?path_info=/projects&token=#########")
        resp = urllib2.urlopen(req2)
        resp_data = resp.read()
        if not resp.code == '200' and resp.headers.get('content-type') == 'text/xml':
          # Do your error handling.
          raise Exception('Unexpected response',req2,resp)
        data = etree.XML(resp_data)
        #assigns the api_id to the id at index of 0 for time being,  using the // in front of project makes sure that its looking at the correct node inside of the projects structure
        api_id = int(data.xpath('//project/id/text()')[0])
        project.API_id = api_id
        project.save()
从现在开始,它将元素放在[0]并存储ID就好了,但我需要最新的/最新的/ etc元素.
谢谢,
史蒂夫
更改[0]为[-1]选择列表中的最后一个元素:
api_id = int(data.xpath('//project/id/text()')[-1])
请注意,如果最大值不在列表的末尾,则可能不会为您提供最大值 id.
要获得最大的id,你可以这样做:
api_id = max(map(int,data.xpath('//project/id/text()')))
| 归档时间: | 
 | 
| 查看次数: | 1277 次 | 
| 最近记录: |