从网址保存XML并阅读 [英] Save XML from Url and read it

查看:77
本文介绍了从网址保存XML并阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作android应用,我需要从URL下载一个xml文件并打开它, 我该怎么做?

I'm making android App and I need to download a xml file from an URL and open it, How I can do this?

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的请求.

It a request from a local directory and non an http request.

推荐答案

以下是适合您的代码段,

Here is code snippet for you ,

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

否则这些链接可以为您提供帮助,

Else these link can help you,

1)在android中读取远程XML

2)下载远程XML并将其存储在android

这篇关于从网址保存XML并阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆