我想解析XML HttpResponse我從一個HttpPost到一個服務器(last.fm),爲一個last.fm android應用程序。如果我簡單地解析它的字符串,我可以看到它是一個普通的XML字符串,具有所有所需的信息。但我只是無法解析單個NameValuePairs。這是我的HttpResponse對象:解析一個XML HttpResponse
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
我嘗試了兩種不同的東西和他們的非工作。首先,我試圖檢索NameValuePairs:
List<NameValuePair> answer = URLEncodedUtils.parse(r_entity);
String name = "empty";
String playcount = "empty";
for (int i = 0; i < answer.size(); i++){
if (answer.get(i).getName().equals("name")){
name = answer.get(i).getValue();
} else if (answer.get(i).getName().equals("playcount")){
playcount = answer.get(i).getValue();
}
}
在此代碼之後,name和playcount仍爲「空」。所以我試圖用一個XML解析器:
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document answer = db.parse(new DataInputStream(r_entity.getContent()));
NodeList nl = answer.getElementsByTagName("playcount");
String playcount = "empty";
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
Node fc = n.getFirstChild();
playcount Url = fc.getNodeValue();
}
這似乎不能早得多,因爲它甚至沒有去設定playcount變量。但就像我說如果我執行此操作:
EntityUtils.toString(r_entity);
我會得到一個完美的XML字符串。所以它應該沒有問題,因爲HttpResponse包含正確的信息。我究竟做錯了什麼?
是的。你是對的。我改變了它,但它但兩個變量仍然保留「空」 – gaussd 2011-02-11 22:21:38