XmlPullParser with inputstream fails with Unexpected token in non-existent text

1.4k Views Asked by At

The XML

        <foo>text</foo>

Parser code copied from http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html

        XmlPullParserFactory pullParserFactory;
        try {    
            pullParserFactory = XmlPullParserFactory.newInstance();
            pullParserFactory.setNamespaceAware(true);
            mParser = pullParserFactory.newPullParser();

            InputStream inputStream = getResources().openRawResource(R.xml.foo);
            mParser.setInput(inputStream, null);
            //mParser.setInput(new StringReader("<foo>text</foo>"));
            int eventType = mParser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if(eventType == XmlPullParser.START_DOCUMENT) {
                    System.out.println("Start document");
                } else if(eventType == XmlPullParser.START_TAG) {
                    System.out.println("Start tag "+mParser.getName());
                } else if(eventType == XmlPullParser.END_TAG) {
                    System.out.println("End tag "+mParser.getName());
                } else if(eventType == XmlPullParser.TEXT) {
                    System.out.println("Text "+mParser.getText());
                }
                eventType = mParser.next();
            }
            System.out.println("End document");

        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

It generates the error below on the first call to next(), but only when using setInput(InputStream, encoding). The example uses setInput(StringReader) which works fine when you use that version of setInput;

06-07 12:35:30.992: W/System.err(30950): org.xmlpull.v1.XmlPullParserException: Unexpected token (position:TEXT ���������������4������...@1:149 in java.io.InputStreamReader@425ceab0)

2

There are 2 best solutions below

0
On BEST ANSWER

Got the answer from yano on this thread: XmlPullParser - unexpected token (android)

You need to move from file from res/xml to assets and get the file with the code:

InputStream in = this.getAssets().open("sample.xml");

Apparently getRawResource() does not read the encoding properly and if you just dump the contents of the inputstream there are plenty of garbage characters.

2
On

Instead of using the InputStream to set the input, what you need is to pass InputStreamReader to the setInput

sample:

xpp.setInput(new InputStreamReader(obinputStreamj));

is -> string

 BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
    total.append(line);
}