大家好,在过去的几天里,我得到了一些惊人的帮助,试图解决我的问题。我只想问最后一个问题(我希望):
我试图从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,但是我需要最新的/newst/etc元素。在
谢谢
史蒂夫
将
[0]
更改为[-1]
,以选择列表中最后一个元素:请注意,如果最大值不在列表的末尾,这可能不会给出最大值
id
值。在要获得最大的
^{pr2}$id
,可以执行以下操作:相关问题 更多 >
编程相关推荐