-->

XmlPullParser is not working with InputStream

2019-02-13 22:25发布

问题:

I am using XmlPullParser for xml parsing in my android app but when I set input as InputStream it not works while I set input as Reader it starts working

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(obj,null);//obj is the object of InputStream
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
                 logger.println("eventType.."+eventType);
              if(eventType == XmlPullParser.START_DOCUMENT) {

                     // control goes here only

              } else if(eventType == XmlPullParser.START_TAG) {
                  //This block never executed
                  }

              } else if(eventType == XmlPullParser.END_TAG) {
                 //This block never executed
              } else if(eventType == XmlPullParser.TEXT) {

              }
              eventType = xpp.next();
             }

Even if I store data from InputStream object in a string and set that String as input then this code also works fine.

xpp.setInput(new StringReader(str));//str contains the data from InputStream

回答1:

The same problem: passing InputStream directly works fine on Android 2.3.3 but doesn't work on 4.1. You can use xpp.setInput(new InputStreamReader(obj));



回答2:

Got the answer for a similar problem 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.