2014-03-26 90 views
0

我想從SD卡讀取一個xml文件。我需要解析它到一個字符串數組。解析來自SD卡的XML android

XML(A.XML)

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string-array name="Timetable"> 
     <item>05:40</item> 
     <item>06:00</item> 
     <item>06:16</item> 
     <item>06:28</item> 
     <item>06:40</item> 
     <item>07:16</item> 
     <item>07:29</item> 
     <item>07:43</item> 
     <item>07:55</item> 
     <item>08:07</item> 
     <item>08:22</item> 
     <item>08:34</item> 
     <item>08:46</item> 
     <item>08:58</item> 
     <item>09:10</item> 
     <item>09:22</item> 
     <item>09:34</item> 
     <item>09:46</item>   
     <item>12:10</item> 
     <item>12:22</item> 
     <item>12:34</item> 
     <item>12:46</item>   
    </string-array> 
</resources> 

我曾嘗試使用兩個不同的功能,並沒有工作,最後一個字符串是空的。

功能1:

public void function(){ 
     String xml = null; 
     try {   
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost("FindMyBus/a.xml"); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      xml = EntityUtils.toString(httpEntity); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 


    } 

功能2:

public void prueba(){ 
     File file = new File(Environment.getExternalStorageDirectory() 
       + "FindMyBus/a.xml"); 

     StringBuilder contents = new StringBuilder(); 
     try { 
       //use buffering, reading one line at a time 
       //FileReader always assumes default encoding is OK! 
       BufferedReader input = new BufferedReader(new FileReader(file)); 
       try { 
       String line = null; //not declared within while loop 
       /* 
       * readLine is a bit quirky : 
       * it returns the content of a line MINUS the newline. 
       * it returns null only for the END of the stream. 
       * it returns an empty String if two newlines appear in a row. 
       */ 
       while ((line = input.readLine()) != null){ 
        contents.append(line); 
        contents.append(System.getProperty("line.separator")); 

       } 
       } 
       finally { 
       input.close(); 
       } 
      } 
      catch (IOException ex){ 
       ex.printStackTrace(); 
      } 

      String data= contents.toString(); 

    } 

誰能幫助我?

回答

0

如果你的XML是在你的應用程序資源,就像它似乎是,你可以這樣做:

String[] array = getResources().getStringArray(R.array.Timetable); 
+0

謝謝,但是xml是從SD卡中獲取的。 – user3302071