开发者

Getting last (newest) element with lxml,python

Hey everyone, I have had some amazing help the past couple days in trying to solve my issue. I just have one last questions (I hope) :)

I am trying to get the last element from my xml and place it in a variable. I am using django,python and the lxml library.

What I want to do is, go through the XML that I have got from the API call, find the newest project, (it will have the largest ID number) then assign it to a variable to store in my database. I am having some trouble finding out how to find that latest, newest, element.

Here is a code snippet:

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.h开发者_如何学JAVAeaders.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()

As of right now, it takes the element at [0] and stores the ID just fine, but I need the latest/newest/etc element instead.

Thanks,

Steve


Change [0] to [-1] to select the last element in the list:

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

Note that this may not give you the largest id value if the largest is not at the end of the list.

To get the largest id, you could do this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜