开发者

Reading XML file from /res/xml using InputStream reader yields invalid characters / encoded data

开发者 https://www.devze.com 2023-02-10 14:58 出处:网络
I\'m having trouble reading in XML data from an XML resource located in /res/xml/testxml.xml. For some reason using examples from my book and online, I\'m not able to read the data properly. The follo

I'm having trouble reading in XML data from an XML resource located in /res/xml/testxml.xml. For some reason using examples from my book and online, I'm not able to read the data properly. The following method is simple; read the XML resource and print the lines within it.

public InputStream fetchLocalStream(String file){
    InputStream in = null;

    try {
        //in = Global.gContext.openFileInput("testxml.xml");
        in = Global.gContext.getResources().openRawResource(R.xml.testxml);
        try {
             if (in != null) {
                  // prepare the file for reading
                开发者_运维百科  InputStreamReader inputreader = new InputStreamReader(in);
                  BufferedReader buffreader = new BufferedReader(inputreader);

                  String line;

                  // read every line of the file into the line-variable, on line at the time
                  while (( line = buffreader.readLine()) != null) {
                      Log.d(Global.TAG,"-->Line:" + line);
                    // do something with the settings from the file
                  }

                }
            } catch (Exception e){}


            return in;
    }catch (Exception e){ Log.d(Global.TAG,"--> Failed!!!!" + e); }
    return in;
}

Any help would be greatly appreciated.

Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜♥└Ç└Ç└Ç#└Ç└Ç└Ƕ└Ƕ└Ç└Ç└Ç└Ç└Ç└Ç└Ç└Ç└Ç♦☺►└Ç∟└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜$└Ç└Ç└└Ç└Ç└Ç└Ç└Ç└Ç└Ç♥☺►└Ç↑└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜♥└Ç└Ç└Ç#└Ç└Ç└Ç☻☺►└Ç$└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜♥└Ç└Ç└Ç%└Ç└Ç└Ƕ└Ƕ└Ç└Ç└Ç└Ç└Ç└Ç└Ç└Ç└Ç♦☺►└Ç∟└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜&└Ç└Ç└└Ç└Ç└Ç└Ç└Ç└Ç└Ç♥☺►└Ç↑└Ç└Ç└Ç
Line:└Ç└Ç└Ç∩┐╜∩┐╜∩┐╜∩┐╜♥└Ç└Ç└Ç%└Ç└Ç└Ç☻☺►└ÇL└Ç└Ç└Ç


I had the same problem and found the solution in the thread "Android SAX xml not well-formed" over at anddev.org:

Found out an interesting stuff - when moving xml file from xml folder to raw, everything works smoothly. I guess that's why the function is called openRawResource . Anyways i think that android adds some stuff to the files stored in non raw folder. But this is just a thinking aloud.

Moving from /res/xml to /res/raw solved the problem for me.


The problem is probably a character encoding issue. Try using the XmlResourceParser, which you can obtain via Resources.getXml. (Most XML parsers are adapt at dealing with character encoding.) Here's an example.

http://developer.android.com/reference/android/content/res/Resources.html

0

精彩评论

暂无评论...
验证码 换一张
取 消