问题描述
我试图解析XML型Htt presponse我从一个HttpPost到服务器(last.fm),对于last.fm的Android应用程序。如果我简单地将它解析为字符串我可以看到它是一个正常的XML字符串,与所有需要的信息。但我只是不能解析单namevaluepairs中。这是我的Htt presponse对象:
I'm trying to parse the XML HttpResponse i get from a HttpPost to a server (last.fm), for a last.fm android app. If i simply parse it to string i can see it being a normal xml string, with all the desired information. But i just cant parse the single NameValuePairs. This is my HttpResponse object:
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
我试过两个不同的东西,非他们的工作。首先,我试图找回namevaluepairs中:
I tried two different things and non of them worked. First i tried to retrieve the 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();
}
}
在此code,姓名和playcount保持空。所以我试图用一个XML解析器:
After this code, name and playcount remain "empty". So i tried to use a XML Parser:
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变量。但是就像我说,如果我执行这样的:
This seems to fail much earlier since it doesn't even get to setting the playcount variable. But like i said if i perform this:
EntityUtils.toString(r_entity);
我会得到一个完美的XML字符串。所以应该没有问题的标准杆,因为工作的Htt presponse包含正确的信息。我究竟做错了什么?
I will get a perfect xml string. So it should no problem to pars it since the HttpResponse contains the correct information. What am i doing wrong?
推荐答案
我解决了它。 DOM的XML解析器需要更多一点的调整:
I solved it. The DOM XML parser needed a little more adjustment:
HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
String xmlString = EntityUtils.toString(r_entity);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc = db.parse(inStream);
String playcount = "empty";
NodeList nl = doc.getElementsByTagName("playcount");
for(int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
playcount = nameElement.getFirstChild().getNodeValue().trim();
}
}
这篇关于解析XML的Htt presponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!