从Url保存XML并读取它

时间:2013-05-02 08:04:21

标签: android xml file parsing

我正在制作Android应用,我需要从xml下载URL文件并将其打开, 我怎么能这样做?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    File dir1 = getDir("xmls",Context.MODE_PRIVATE);//Creating an internal dir;
    System.out.println("dir1: " + dir1);

    //Saving The File
    try {
       URL url = new URL("http://www. the url of my xml .xml");
       // The server thinks this request is from an Opera browser!
       String userAgent = "Opera/9.63 (Windows NT 5.1; U; en) Presto/2.1.1";
       System.out.println("Downloading ...");
       downloadFromUrl(url, dir1+"news.xml", userAgent);
       System.out.println("OK");
} catch (Exception e) {
        System.err.println(e);
        System.out.println("Entri pure nel catch");
    }
    //This is the path of the xml file that i have saved
    URL = dir1+"/news.xml" ; 
    ArrayList<HashMap<String, String>> songsList = 
                                       new ArrayList<HashMap<String, String>>();
    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML from UR
    Document doc = parser.getDomElement(xml); // getting DOM element
    //And then i do all the parsing
    NodeList nl = doc.getElementsByTagName(KEY_CATEGORIA);

XMlParser类是这样的:

public class XMLParser_Categorie {

// constructor
public XMLParser_Categorie() {

}

/**
 * Getting XML from URL making HTTP request
 * @param url string
 * */
public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        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();
    }
    // return XML
    return xml;
}

我需要更改此说明:

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

来自本地目录的请求而非http请求。

1 个答案:

答案 0 :(得分:0)

以下是您的代码段,

  try {

        URL url = new URL("your url goes here");

        //create the new connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        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 = Environment.getExternalStorageDirectory();
        //create a new file, specifying the path, and the filename
        //which we want to save the file as.
        File file = new File(SDCardRoot,"Demo.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();
        progressDialog.setMax(totalSize);

        //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;

        }
        //close the output stream when done
        fileOutput.close();
        //catch some possible errors...
} catch (MalformedURLException e) {
        e.printStackTrace();
} catch (IOException e) {
        e.printStackTrace();
}

这些链接可以帮助您,

1)Read remote XML in android

2)Download remote XML and store it in android