Wednesday, October 16, 2013

Parser XML via XmlPullParser in Android app

It's easy and simple to use XmlPullParser in Android app, the key method is next(). Call next() to go to next tag in XML, then adjust the current position by the event type. Just notice there is a TEXT event with empty value between two lines.

Here is how to parser a asset XML file:

            InputStream is = getAssets().open("colors.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(is, null);
            int eventType = parser.getEventType();
          
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_DOCUMENT) {
                    System.out.println("Start document");
                } else if (eventType == XmlPullParser.START_TAG) {
                    System.out.println("Start tag " + parser.getName());
                } else if (eventType == XmlPullParser.END_TAG) {
                    System.out.println("End tag " + parser.getName());
                } else if (eventType == XmlPullParser.TEXT) {
                    System.out.println("Text " + parser.getText());
                }
                eventType = parser.next();
            }
            System.out.println("End document");
            is.close();


No comments:

Post a Comment

Thrift fails on Windows - thrift failed error: The command line is too long.

Meet a thrift compiling failure on my project on Windows 7. Using Maven in IntelliJ so I choiced maven-thrift-pluging for thrift files. For ...