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

后端 未结 3 1640
醉梦人生
醉梦人生 2020-12-05 06:13

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 tr

3条回答
  •  离开以前
    2020-12-05 06:38

    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 RuntimeException("Cannot parse XML");
    }
    catch (IOException e) {
        throw new RuntimeException("Cannot parse XML");
    }
    finally {
        parser.close();
    }
    

    If you want to parse XML that's not from a resource file you could create a new XmlPullParser using the XmlPullParserFactory class and then call the setInput() method.

提交回复
热议问题