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