2010-11-17 147 views
1

嗨大家好,我過去幾天在嘗試解決我的問題時得到了一些驚人的幫助。我只有最後一個問題(我希望):)使用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蠻好的元素,但我需要的最新/最新/等元素來代替。

感謝,

史蒂夫

+0

是要素有序,即會在一個ID最大是最後的XML? (如果是這樣,Ubuntu的正確答案)。 – delnan 2010-11-17 17:04:23

回答

5

變化[0][-1]選擇在列表中最後元素:

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

注意,這可能不會給你的最大id值如果最大的不在列表的末尾。

要獲得最大的id,你可以這樣做:

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

完美,我不知道爲什麼我沒有早點想到! – TheLifeOfSteve 2010-11-17 17:10:55

+0

沒問題;很高興我能幫上忙。 – unutbu 2010-11-17 17:11:30