Alex Rivera | Logout

Way to parse XML (org.w3c.Document) on Android

Asked 2009-12-18T10:22:58.097
10

Can anyone point me to a explanation for or explain to me how I can easily parse the XML and get values of a w3c.Document on Android using only Android OS Libs?

I tried to use a implementation of dom4j, but it is very slow :-(

Edit
Report

1 Answer

15

Here's an article at Developer.com comparing the performance of the DOM, SAX and Pull parsers on Android. It found the DOM parser to be by far the slowest, then the Pull parser and the SAX parser the fastest in their test.

If you're going to be a doing a lot of parsing in your application it may be worth benchmarking the different options to see which works best for you.

I've used the XmlPullParser via XmlResourceParser and found that worked well and was easy to use.

It works through the XML returning events telling you what it's found in there.

If you use it, your code will look something like this:

XmlResourceParser parser = context.getResources().getXml(R.xml.myfile);

try {
    int eventType = parser.getEventType();

    while (eventType != XmlPullParser.END_DOCUMENT) {
        String name = null;

        switch (eventType){
            case XmlPullParser.START_TAG:
                name = parser.getName().toLowerCase();

                if (name.equals(SOME_TAG)) {
                    for (int i = 0;i < parser.getAttributeCount();i++) {
                        String attribute = parser.getAttributeName(i).toLowerCase();

                        if (attribute.equals("myattribute")) {
                            String value = parser.getAttributeValue(i);
                        }

                    }
                }

                break;
            case XmlPullParser.END_TAG:
                name = parser.getName();
                break;
        }

        eventType = parser.next();
    }
}
catch (XmlPullParserException e) {
    throw new Run
answered 2009-12-18T11:06:20.023

Your Answer