我正在尝试解析从 HttpPost 到服务器(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();
}
}
在此代码之后,名称和播放次数仍为“空”。所以我尝试使用 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 包含正确的信息。我究竟做错了什么?