XmlPullParser is not working with InputStream

痴心易碎 提交于 2019-12-19 03:21:57

问题


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.



来源:https://stackoverflow.com/questions/11190494/xmlpullparser-is-not-working-with-inputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!