2013-10-18 17 views
-3

我正在開發一個Android應用程序,並且使用位於此位置的SD卡上的XML文件sdcard/XML_folder/webservices.xml。您可以在http://data.gov.in/sites/default/files/Date-Wise-Prices-all-Commodity.xml上看到我的XML文件。如何獲取我的SD卡上的xml數據

現在,如果你已經看到了我的XML文件。所以,我想從我的SD卡上的XML文件解析(獲取)所有狀態名稱。這次我只想顯示列表中的所有狀態名稱(下拉菜單)。

請給我一個使用我的XML文件的例子。

我很迷惑,看到網上的很多例子。所以,請用我的XML文件告訴我。

在此先感謝。

+0

嘗試此鏈接,它可以幫助你http://qtcstation.com/2011/01/parsing-xml-from-the-sdcard-using-xmlpullparser/ –

+0

@matheszabi:我在谷歌搜索,而不是得到解決方案..我有很多困惑...所以請告訴我用我的XML ..請 – Shiv

+0

打開谷歌和鍵入:「java如何解析XML」 –

回答

1

試試這個。

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
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; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 
import android.os.AsyncTask; 
import android.os.Build; 
import android.os.Bundle; 
import android.annotation.TargetApi; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.view.Menu; 

public class FileActivity extends Activity { 


    // Progress dialog 
    ProgressDialog pDialog; 

    @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_file); 

     String data = "http://data.gov.in/sites/default/files/Date-Wise-Prices-all-Commodity.xml"; 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) 
      new XmlParsing(data).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null}); 
     else 
      new XmlParsing(data).execute(new String[]{null}); 


    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    public class XmlParsing extends AsyncTask<String, Void, String> { 

     // variables passed in: 
     String data; 
     // constructor 
     public XmlParsing(String data) { 
      this.data = data; 
     } 

     @Override 
     protected void onPreExecute() { 
      pDialog = ProgressDialog.show(FileActivity.this, "Fetching Details..", "Please wait...", true); 
     } 


     @Override 
     protected String doInBackground(String... params) { 
      // TODO Auto-generated method stub 

      try {    

       URL url = new URL(data); 

       //create the new connection 

       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

       //set up some things on the connection 

       urlConnection.setRequestMethod("GET"); 

       urlConnection.setDoOutput(true); 

       //and connect! 

       urlConnection.connect(); 

       //set the path where we want to save the file 

       //in this case, going to save it on the root directory of the 

       //sd card. 

       File SDCardRoot = new File("/sdcard/"); 

       //create a new file, specifying the path, and the filename 

       //which we want to save the file as. 

       File file = new File(SDCardRoot,"hello.xml"); 

       //this will be used to write the downloaded data into the file we created 

       FileOutputStream fileOutput = new FileOutputStream(file); 

       //this will be used in reading the data from the internet 

       InputStream inputStream = urlConnection.getInputStream(); 

       //this is the total size of the file 

       int totalSize = urlConnection.getContentLength(); 

       //variable to store total downloaded bytes 

       int downloadedSize = 0; 

       //create a buffer... 

       byte[] buffer = new byte[1024]; 

       int bufferLength = 0; //used to store a temporary size of the buffer 

       //now, read through the input buffer and write the contents to the file 

       while ((bufferLength = inputStream.read(buffer)) > 0) 

       { 

       //add the data in the buffer to the file in the file output stream (the file on the sd card 

       fileOutput.write(buffer, 0, bufferLength); 

       //add up the size so we know how much is downloaded 

       downloadedSize += bufferLength; 

       int progress=(int)(downloadedSize*100/totalSize); 

       //this is where you would do something to report the prgress, like this maybe 

       //updateProgress(downloadedSize, totalSize); 

       } 

       //close the output stream when done 

       fileOutput.close(); 


       InputStream is = new FileInputStream(file.getPath()); 
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
       DocumentBuilder db = dbf.newDocumentBuilder(); 
       Document doc = db.parse(new InputSource(is)); 
       doc.getDocumentElement().normalize(); 

       NodeList nodeList = doc.getElementsByTagName("Table"); 

       for (int i = 0; i < nodeList.getLength(); i++) { 

        Node node = nodeList.item(i);  

        Element fstElmnt = (Element) node; 
        NodeList nameList = fstElmnt.getElementsByTagName("State"); 
        Element nameElement = (Element) nameList.item(0); 
        nameList = nameElement.getChildNodes(); 



        System.out.println("State : "+((Node) nameList.item(0)).getNodeValue()); 

       } 

      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (ParserConfigurationException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (SAXException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


      return null; 
     } 


     @Override 
     protected void onPostExecute(String result) { 
      // Now we have your JSONObject, play around with it. 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 

     } 

    } 
} 

在日誌中的所有國家的名字將顯示

+0

文件沒有得到保存在SD卡 – Shiv

+0

@Shiv你給SD卡權限.. – Hariharan

+0

'<使用權限android:name =「android.permission.WRITE_EXTERNAL_STORAGE」/> <使用權限android:na我=「android.permission.INTERNET」/>'這? – Shiv