我想解析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