2011-02-11 98 views
10

我想解析XML HttpResponse我從一個HttpPost到一個服務器(last.fm),爲一個last.fm android應用程序。如果我簡單地解析它的字符串,我可以看到它是一個普通的XML字符串,具有所有所需的信息。但我只是無法解析單個NameValuePairs。這是我的HttpResponse對象:解析一個XML 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(); 
} 

這似乎不能早得多,因爲它甚至沒有去設定playcount變量。但就像我說如果我執行此操作:

EntityUtils.toString(r_entity); 

我會得到一個完美的XML字符串。所以它應該沒有問題,因爲HttpResponse包含正確的信息。我究竟做錯了什麼?

回答

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時,這是非常好的tutorial。 你可以用它來構建需要解析XML提要更強大的應用程序 我希望它能幫助

0

如果(answer.get(I).getName()== 「名」){

您不能使用==比較字符串

當我們使用==運算符時,實際上我們正在比較兩個對象引用,以查看它們是否指向同一個對象。例如,我們無法使用==運算符比較兩個字符串是否相等。我們必須使用.equals方法,它是由java.lang.Object的所有類繼承的方法。

以下是比較兩個字符串的正確方法。

String abc = "abc"; String def = "def"; 

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

Top Ten Errors Java Programmers Make

+0

是的。你是對的。我改變了它,但它但兩個變量仍然保留「空」 – gaussd 2011-02-11 22:21:38