-3

我正在开发一个 Android 应用程序,并且我正在使用一个 XML 文件,该文件位于我的 SD 卡上的这个位置sdcard/XML_folder/webservices.xml。你可以看到我的 XML 文件http://data.gov.in/sites/default/files/Date-Wise-Prices-all-Commodity.xml

现在,如果您看到了我的 XML 文件。所以,我想从我的 sdcard 上的那个 XML 文件中解析(获取)所有状态名称。这次我只想在列表中显示所有状态名称(下拉)。

请给我一个使用我的 XML 文件的例子。

我很困惑在网上看到很多例子。所以,请告诉我使用我的 XML 文件。

提前致谢。

4

1 回答 1

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();

        }

    }
}

在日志中将显示所有状态名称

于 2013-10-19T04:54:30.877 回答