嗨大家好,我过去几天在尝试解决我的问题时得到了一些惊人的帮助。我只有最后一个问题(我希望):)使用lxml获取最新(最新)元素,python
我想从我的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蛮好的元素,但我需要的最新/最新/等元素来代替。
感谢,
史蒂夫
是要素有序,即会在一个ID最大是最后的XML? (如果是这样,Ubuntu的正确答案)。 – delnan 2010-11-17 17:04:23