XmlPullParser 解析不到END_DOCUMENT,XmlPullParserException: Unexpected token (position:TEXT

最近遇到一个坑,我在网上找了一段代码来解析XML,片段如下:

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

但调试时发现程序怎么在解析到XML文件末尾,调用XmlPullParser.next()函数时,会报 

 Android-org.xmlpull.v1.XmlPullParserException: Unexpected token (position:TEXT的错误,原因是在文件末尾,next()函数没有返回END_DOCUMET,故Parser会一直解析下去而报错。解决方案是在While循环的判断条件加上到达xml文件末尾的判断,代码如下:

final int depth = parser.getDepth();

        int type = parser.next();
while ((type != XmlPullParser.END_TAG || parser
                .getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
...//next
}


你可能感兴趣的:(xml,android)