XmlPullParser cannot parse END_DOCUMENT, XmlPullParserException: Unexpected token (position: TEXT, unexpectedtoken
Recently, I encountered a pitfall. I found a piece of code on the Internet to parse XML. The snippets are as follows:
int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if(eventType == XmlPullParser.START_DOCUMENT) { System.out.println("Start document"); } else if(eventType == XmlPullParser.END_DOCUMENT) { System.out.println("End document"); } else if(eventType == XmlPullParser.START_TAG) { System.out.println("Start tag "+xpp.getName()); } else if(eventType == XmlPullParser.END_TAG) { System.out.println("End tag "+xpp.getName()); } else if(eventType == XmlPullParser.TEXT) { System.out.println("Text "+xpp.getText()); } eventType = xpp.next(); }
However, when debugging, how does the program parse to the end of the XML file and call the XmlPullParser. next () function?
Android-org.xmlpull.v1.XmlPullParserException: Unexpected token (position: TEXT error, because at the end of the file, the next () function does not return end_et et, so Parser will continue to parse and report an error. The solution is to add the While LOOP judgment condition to the judgment at the end of the xml file. The Code is as follows:
final int depth = parser.getDepth(); int type = parser.next();while ((type != XmlPullParser.END_TAG || parser .getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {...//next}