从url获取XML文件会产生错误的输出

时间:2013-05-03 15:16:01

标签: xml-parsing jsoup

我在这个奇怪的问题上结束了我的智慧。我试图从网址下载(或复制)一个xml文件到我的Android手机(Desire HD v2.3.3)。根据SOF的许多人的说法,它应该开箱即用,但无论我如何尝试以及我遵循的教程,它根本不起作用。据我所知,我没有得到所需的xml文件。

logcat没有显示任何特殊的东西,我用字符串消息跟踪我的代码。

以下是我的代码:

private void programXmlExists() {
        //Kontrollerar om XML-filern Program.xml existerar annars skall den laddas ner.
        //Om filen existerar, så skall filens timestamp jämföras med dagens. Är det större skillnad än kl. 00.00
        //så skall en ny uppdatering ske.
        if(xmlFileExistence("Program.xml")){
            Toast.makeText(this, "1) Program.xml exists ", Toast.LENGTH_SHORT).show();
            System.out.println("1) File exists");
            //Filen Program.xml existerar. Kolla om filens timestamp är yngre än 00.00 Om så ej är fallet, så skall en uppdaterad version
            //hämtas från servern
            File file = getBaseContext().getFileStreamPath("Program.xml");
            file = new File(this.getFilesDir().getAbsolutePath() + "Program.xml");
            long date = file.lastModified();
            //Toast.makeText(this, "Date: "+date, Toast.LENGTH_SHORT).show();

            //Glöm ej att radera den gamla Program.xml om den behöver uppdateras
            //deleteFile("Program.xml");

            //downloaderThread = new Thread(this, "http://ken.nu/projekt/Program.xml");
            //downloaderThread.start();             
            /**
             * Connects to the URL of the file, begins the download, and notifies the
             * AndroidFileDownloader activity of changes in state. Writes the file to
             * the root of the SD card.
             */

            URL url = null;
            URLConnection conn = null;
            int fileSize, lastSlash;
            String fileName;
            BufferedInputStream inStream = null;;
            BufferedOutputStream outStream = null;;
            File outFile;
            FileOutputStream fileStream = null;
            Message msg;

            // We're going to connect now
            try {
                url = new URL("http://ken.nu/projekt/Program.xml");
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                conn = url.openConnection();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            conn.setUseCaches(false);
            fileSize = conn.getContentLength();

            // get the filename
            lastSlash = url.toString().lastIndexOf('/');
            fileName = "Program.xml";
            if(lastSlash >=0)
            {
                    fileName = url.toString().substring(lastSlash + 1);
            }
            if(fileName.equals(""))
            {
                    fileName = "Program.xml";
            }

         // start download
            try {
                inStream = new BufferedInputStream(conn.getInputStream());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            outFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
            try {
                fileStream = new FileOutputStream(outFile);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
            byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
            int bytesRead = 0, totalRead = 0;
            try {
                while((bytesRead = inStream.read(data, 0, data.length)) >= 0)
                {
                        outStream.write(data, 0, bytesRead);
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }


            try {
                outStream.close();
                fileStream.close();
                inStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            xmlFileExistence("Program.xml");

        }else{

            //Programs.xml finns inte. Ladda ner en ny version utav den från servern

            Toast.makeText(this, "Program.xml DOESNT exist ", Toast.LENGTH_SHORT).show();
            System.out.println("2) Does not exist");
            File dir = getFilesDir();
            //Filen existerar inte. Hämta en ny version från servern
            String FILENAME = "Program.xml";
            // File url to download
            String file_url = "http://ken.nu/projekt/Program.xml";


            //------------
            /**
             * Connects to the URL of the file, begins the download, and notifies the
             * AndroidFileDownloader activity of changes in state. Writes the file to
             * the root of the SD card.
             */

            URL url = null;
            URLConnection conn = null;
            int fileSize, lastSlash;
            String fileName;
            BufferedInputStream inStream = null;;
            BufferedOutputStream outStream = null;;
            File outFile;
            FileOutputStream fileStream = null;
            Message msg;

            // We're going to connect now
            try {
                url = new URL("http://ken.nu/projekt/Program.xml");
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                conn = url.openConnection();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            conn.setUseCaches(false);
            fileSize = conn.getContentLength();

            // get the filename
            lastSlash = url.toString().lastIndexOf('/');
            fileName = "Program.xml";
            if(lastSlash >=0)
            {
                    fileName = url.toString().substring(lastSlash + 1);
            }
            if(fileName.equals(""))
            {
                    fileName = "Program.xml";
            }

         // start download
            try {
                inStream = new BufferedInputStream(conn.getInputStream());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            outFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
            try {
                fileStream = new FileOutputStream(outFile);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
            byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
            int bytesRead = 0, totalRead = 0;
            try {
                while((bytesRead = inStream.read(data, 0, data.length)) >= 0)
                {
                        outStream.write(data, 0, bytesRead);
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }


            try {
                outStream.close();
                fileStream.close();
                inStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            xmlFileExistence("Program.xml");
            //------------

        }
        //deleteFile("Program.xml");
        System.out.println("3) End");
}

这是我的loadSpinnerPrograms()。

private void loadSpinnerPrograms() {
    List<String> SpinnerProgramsArray =  new ArrayList<String>();
    spinnerPrograms = (Spinner) findViewById(R.id.spinner_programs);

    //Code input to spinner

    Document doc = null;

    /*
    try {
        doc = Jsoup.connect("http://ken.nu/projekt/Program.xml").get();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }*/

    doc = Jsoup.parse("Program.xml", "utf-8");
    System.out.println("loadSpinnerPrograms: "+doc.toString());

    Elements id = doc.getElementsByTag("id"); //Hämta alla element som finns med tagen id
    Elements namn = doc.getElementsByTag("namn"); //Hämta alla element som finns med tagen namn

    int i = 0;
    //Denna forsats används för att få ut elementen id och namn som finns i elementen kurs
    //och lägga till dem i SpinnersArray
    for (Element e : doc.select("kurs")){
        System.out.println("id: "+id.get(i).text()+"   namn: "+namn.get(i).text());
        SpinnerProgramsArray.add(id.get(i).text()+" - "+namn.get(i).text());
        i++;
    }
    System.out.println("Programs counter: "+i);

    ArrayAdapter<String> adapterProg = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SpinnerProgramsArray);
    adapterProg.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinnerPrograms.setAdapter(adapterProg);
    spinnerPrograms.setOnItemSelectedListener(this);

    /*
     * Denna kod användes för testning när man laddade in items från en xml-.fil
    spinnerPrograms = (Spinner) findViewById(R.id.spinner_programs);
    ArrayAdapter<CharSequence> adapterProg = ArrayAdapter.createFromResource( this, R.array.programs_array, android.R.layout.simple_spinner_item); 
    adapterProg.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerPrograms.setAdapter(adapterProg);
    spinnerPrograms.setOnItemSelectedListener(this);
    */

}

我真正想到的是输出文件在我尝试读取其中的元素时会给出这个。如果我尝试读取文件,我会得到html-tags,并在正文中显示Programs.xml 我希望该文件包含在线的xml文件。 谁能帮助我了解我做错了什么?我真的很有智慧。

问候,SM

1 个答案:

答案 0 :(得分:0)

  • 元素namn并不总是存在。
  • 下载的文件只包含文件名!

下载文件和从中读取xml的代码:

byte[] bytes = Jsoup.connect("http://ken.nu/projekt/Program.xml")
        .ignoreContentType(true)
        .execute()
        .bodyAsBytes();

try {
    FileOutputStream fos = new FileOutputStream(file);

    fos.write(bytes);
    fos.close();
} catch (Exception e) {
    e.printStackTrace();
}

Document doc = Jsoup.parse(file, "UTF-8");

Elements kurses = doc.getElementsByTag("kurs");

for (Element kurs : kurses) {
    String id = kurs.getElementsByTag("id").first().text();
    Element namnElement = kurs.getElementsByTag("namn").first();
    String namn = namnElement != null ? namnElement.text() : "";
    System.out.println(id + " : " + namn);
}