我正在尝试解析从HttpServer(last.fm)获得的XML HttpResponse,用于last.fm Android应用程序。如果我只将其解析为字符串,我可以看到它是一个正常的xml字符串,其中包含所有所需的信息。但我无法解析单个NameValuePairs。这是我的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();
}
这个问题似乎在更早的阶段就出了问题,因为它甚至没有设置播放计数变量。但是就像我之前说的,如果我执行这个操作:
EntityUtils.toString(r_entity);
我将获得一个完美的XML字符串。因此,解析它应该没有问题,因为HttpResponse包含了正确的信息。我做错了什么?