XmlPullParser is not working with InputStream
Asked Answered
G

2

6

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
Gehrke answered 25/6, 2012 at 13:45 Comment(6)
what does the xml declaration (i.e. the "<?xml version="1.0" encoding="UTF-8" ?>" part) in your document look like?Booted
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <res_transfer ip="" uuid="" type="2" cons_tf_id="" prod_tf_id=""> <file_data type="0" name="" chunkno="" totalchunks="" md5="" bytes="" /> </res_transfer> this is my xml structureGehrke
Can you post the code where you create obj?Hake
InputStram obj=socket.getInputStream();Gehrke
Do you perform any action in the loop (apart from checking the eventType)? Maybe it is related to the namespace awareness, try to remove the line factory.setNamespaceAware(true); and see if that helps...Hake
I already tried but it not workedGehrke
O
4

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));

Offbeat answered 29/1, 2013 at 8:25 Comment(1)
Running Android 4.3 and InputStreamReader generates the same error.Sarto
S
0

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.

Sarto answered 7/6, 2014 at 17:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.