2012-08-09 3 views
0

나는 단지 내 목록에 첫 번째 <song> 만 가져 오려고합니다. 사용중인 코드를 잘 작동하지만 내 목록에 비슷한 태그 (<song>)의 마지막 항목 만 가져옵니다. 내가 피드가 곡의 변화에 ​​따라 업데이트 될 때, 첫 번째 목록 항목을 검색 할 (그리고 난의 상단에 항상 현재 재생중인 노래를 원하는 :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> 

내 코드 : 여기 내 XML이다 목록)

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에서 외부 for 루프를 중단해야합니다. 이 같은, 내가 XPath를 사용하여 선호하는 것 플래그를 설정하고

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

의에서 테스트하여, 예를 들어,이 작업을 수행 할 수 있습니다

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 메서드가 작동했습니다. 매우 감사. –

+0

당신을 진심으로 환영합니다. for의 조건이 잘못 되었기 때문에 플래그 메소드가 작동하지 않았습니다 (OR이고 AND 여야 함). 나는 그것을 바로 잡기위한 답을 편집했다. – ecdpalma

관련 문제