解析XML HttpResponse

gau*_*ssd 10 xml parsing android httpresponse http-post

我正在尝试将我从HttpPost获取的XML HttpResponse解析为服务器(last.fm),用于last.fm android应用程序.如果我简单地将其解析为字符串,我可以看到它是一个普通的xml字符串,包含所有需要的信息.但我只是无法解析单个NameValuePairs.这是我的HttpResponse对象:

HttpResponse response = client.execute(post);
HttpEntity r_entity = response.getEntity();
Run Code Online (Sandbox Code Playgroud)

我尝试了两种不同的东西,而不是它们都有效.首先,我试图检索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();
   }
}
Run Code Online (Sandbox Code Playgroud)

在此代码之后,name和playcount保持"空".所以我尝试使用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();
}
Run Code Online (Sandbox Code Playgroud)

这似乎很早就失败了,因为它甚至没有设置playcount变量.但就像我说的,如果我执行此操作:

EntityUtils.toString(r_entity);
Run Code Online (Sandbox Code Playgroud)

我会得到一个完美的xml字符串.因此,解析它应该没有问题,因为HttpResponse包含正确的信息.我究竟做错了什么?

gau*_*ssd 17

我解决了 DOM XML解析器需要更多调整:

        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();
             }
        }
Run Code Online (Sandbox Code Playgroud)