android – 解析XML HttpResponse

前端之家收集整理的这篇文章主要介绍了android – 解析XML HttpResponse前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图解析我从HttpPost到一个服务器(last.fm)的一个last.fm android应用程序的 XML HttpResponse.如果我只是解析它到字符串我可以看到它是一个正常的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();
}

这似乎失败得太早了,因为它甚至没有设置playcount变量.但是就像我说的,如果我这样做:

EntityUtils.toString(r_entity);

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

解决方法

解决了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();
             }
        }
原文链接:https://www.f2er.com/android/311806.html

猜你在找的Android相关文章