用lxml和Python获取最后一个元素

1 投票
1 回答
2361 浏览
提问于 2025-04-16 07:13

大家好,最近几天我得到了很多很棒的帮助,正在努力解决我的问题。现在我只剩下一个最后的问题(希望是这样) :)

我想从我的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,但我需要的是最新的元素。

谢谢,

Steve

1 个回答

5

[0] 改成 [-1] 就可以选择列表中的最后一个元素:

api_id = int(data.xpath('//project/id/text()')[-1])

需要注意的是,如果最大的 id 值不在列表的最后面,这样做可能得不到最大的 id 值。

如果想要得到最大的 id,你可以这样做:

api_id = max(map(int,data.xpath('//project/id/text()')))

撰写回答