2012-08-09 23 views
0

我只是試圖在我的列表中獲得第一個<song>;我使用的代碼正常工作,但只能獲取列表中類似標記(<song>)的最後一個條目。這裏是我的XML:Android DOM解析器,獲取列表中的第一項

<songs id="stationid"> 
<song> 
<title> 
<![CDATA[ Last Breath ]]> 
</title> 
<artist> 
<![CDATA[ Xela ]]> 
</artist> 
<album> 
<![CDATA[ For Frosty Mornings And Summer Nights ]]> 
</album> 
<albumart> 
<![CDATA[ ]]> 
</albumart> 
<date>1344536317</date> 
</song> 
<song> 
<title> 
<![CDATA[ Turn On Switch Off (Starring Valerie Trebeljahr) ]]> 
</title> 
<artist> 
<![CDATA[ Static ]]> 
</artist> 
<album> 
<![CDATA[ Flavour Has No Name ]]> 
</album> 
<albumart> 
<![CDATA[ ]]> 
</albumart> 
<date>1344536000</date> 
</song> 
<song> 
<title> 
<![CDATA[ Aim Low ]]> 
</title> 
<artist> 
<![CDATA[ Sheik & Beige ]]> 
</artist> 
<album> 
<![CDATA[ Sty Wars - A Collection of Por ]]> 
</album> 
<albumart> 
<![CDATA[ ]]> 
</albumart> 
<date>1344531485</date> 
</song> 
    </songs> 

和我的代碼:(我只想獲取第一個列表項,作爲飼料的歌曲的變化更新,我想當前播放的歌曲它總是在的頂部列表)

package com.example.networking; 

import android.app.Activity; 
import android.os.Bundle; 

import java.io.IOException; 
import java.io.InputStream; 

import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLConnection; 
import android.util.Log; 

import android.widget.ImageView; 
import android.widget.Toast; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.AsyncTask; 

import java.io.InputStreamReader; 

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 

import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 

public class NetworkingActivity extends Activity { 

    private InputStream OpenHttpConnection(String urlString) 
    throws IOException 
    { 
     InputStream in = null; 
     int response = -1; 

     URL url = new URL(urlString); 
     URLConnection conn = url.openConnection(); 

     if (!(conn instanceof HttpURLConnection))      
      throw new IOException("Not an HTTP connection");   
     try{ 
      HttpURLConnection httpConn = (HttpURLConnection) conn; 
      httpConn.setAllowUserInteraction(false); 
      httpConn.setInstanceFollowRedirects(true); 
      httpConn.setRequestMethod("GET"); 
      httpConn.connect(); 
      response = httpConn.getResponseCode();     
      if (response == HttpURLConnection.HTTP_OK) { 
       in = httpConn.getInputStream();         
      }      
     } 
     catch (Exception ex) 
     { 
      Log.d("Networking", ex.getLocalizedMessage()); 
      throw new IOException("Error connecting"); 
     } 
     return in;  
    } 




private String WordDefinition(String word) { 
    InputStream in = null; 
    String strDefinition = ""; 
    try { 
     in = OpenHttpConnection(
"http://api.somafm.com/songs/groovesalad.xml"); 
     Document doc = null; 
     DocumentBuilderFactory dbf = 
      DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db;    
     try { 
      db = dbf.newDocumentBuilder(); 
      doc = db.parse(in); 
     } catch (ParserConfigurationException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }    
     doc.getDocumentElement().normalize(); 

     //---retrieve all the <song> elements--- 
     NodeList definitionElements = 
      doc.getElementsByTagName("song"); 

     //---iterate through each <song> elements--- 
     for (int i = 0; i < definitionElements.getLength(); i++) { 
      Node itemNode = definitionElements.item(i); 
      if (itemNode.getNodeType() == Node.ELEMENT_NODE) 
      {    
       //---convert the song node into an Element--- 
       Element definitionElement = (Element) itemNode; 

       //---get all the <artist> elements under 
       // the <song> element--- 
       NodeList wordDefinitionElements = 
        (definitionElement).getElementsByTagName(
        "artist"); 

       strDefinition = ""; 
       //---iterate through each <artist> elements--- 
       for (int j = 0; j < wordDefinitionElements.getLength(); j++) {      
        //---convert an <artist> node into an Element--- 
        Element wordDefinitionElement = 
         (Element) wordDefinitionElements.item(j); 

        //---get all the child nodes under the 
        // <artist> element--- 
        NodeList textNodes = 
         ((Node) wordDefinitionElement).getChildNodes(); 

        strDefinition += 
         ((Node) textNodes.item(0)).getNodeValue() + ". \n";  
       } 

      } 
     } 
    } catch (IOException e1) { 
     Log.d("NetworkingActivity", e1.getLocalizedMessage()); 
    } 
    //---return the definitions of the word--- 
    return strDefinition; 
} 

private class AccessWebServiceTask extends AsyncTask<String, Void, String> { 
    protected String doInBackground(String... urls) { 
     return WordDefinition(urls[0]); 
    } 

    protected void onPostExecute(String result) { 
     Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show(); 
    } 
} 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    //---access a Web Service using GET--- 
     new AccessWebServiceTask().execute("apple"); 

} 
} 

謝謝,如果有人可以幫助我!

回答

0

當您第一次打開內循環中的最後一條語句時,您應該在WordDefinition中打開外循環。你可以這樣做,例如,通過設置一個標誌,並在測試它

boolean flag = false;  
for (int i = 0; i < definitionElements.getLength && !flag; i++) { 
... 
    strDefinition += 
        ((Node) textNodes.item(0)).getNodeValue() + ". \n"; 
    flag = true; 
    break; 

我寧願使用XPath,就像這樣:

private String WordDefinition(String word) { 
    InputStream in = null; 
    String strDefinition = ""; 
    XPathFactory xPathFactory = XPathFactory.newInstance(); 
    XPath xPath = xPathFactory.newXPath(); 

    try { 
     in = OpenHttpConnection(
       "http://api.somafm.com/songs/groovesalad.xml"); 
     XPathExpression xPathExpression = xPath.compile("/songs/song[1]/artist"); 
     Node node = (Node) xPathExpression.evaluate(new InputSource(in), XPathConstants.NODE); 
     strDefinition = node.getTextContent(); 
    } 
    catch (IOException e1) { 
     Log.d("NetworkingActivity", e1.getLocalizedMessage()); 
    } 
    catch (XPathExpressionException e1) { 
     Log.d("NetworkingActivity", e1.getLocalizedMessage()); 
    } 
    // ---return the definitions of the word--- 
    return strDefinition; 
} 
+0

太謝謝你了! XPath方法奏效,但布爾標誌仍然從列表底部返回藝術家。非常感激。 – 2012-08-10 21:04:16

+0

不客氣。標誌方法不起作用,因爲for中的條件錯了(它是OR,應該是AND)。我編輯了答案來糾正它。 – ecdpalma 2012-08-15 15:18:46