解析XML HttpResponse

10

我正在尝试解析从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包含了正确的信息。我做错了什么?

3个回答

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();
             }
        }

1

这是一篇非常好的教程,可以帮助你从一个数据源中解析XML。 你可以使用它来构建更加健壮的应用程序,需要解析XML数据源。 希望对你有所帮助。


0
如果 (answer.get(i).getName() == "name") { 你不能使用 == 来比较字符串
当我们使用 == 运算符时,实际上是在比较两个对象引用,以查看它们是否指向同一个对象。我们不能使用 == 运算符来比较两个字符串是否相等。我们必须使用 .equals 方法,这是从 java.lang.Object 继承的方法。
以下是比较两个字符串的正确方法。
 String abc = "abc"; String def = "def";

// Bad way
if ( (abc + def) == "abcdef" )
 {
   ......
 }
 // Good way
 if ( (abc + def).equals("abcdef") )
 {
  .....
 }

摘自Java程序员常犯的十个错误


是的,你说得对。我已经更改了它,但两个变量仍然保持“空白”。 - gaussd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接