Android : Parse using xmlpullparser

北慕城南 提交于 2019-12-25 06:37:16

问题


I have a xml file in the location res/xml/data.xml I need to parse that xml file

XmlResourceParser xrp=context.getResources().getXml(R.xml.data);

I used this code to get that file. It returns as XmlResourceParser Also tried with xmlpullparser

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();

I am not getting clear idea between these two parser. My question is how to parse a xml file in the resource folder using xmlpullparser?


回答1:


XmlResourceParser is an interface which extends XmlPullParser.

getXml wil return the XmlResourceParser object. You can read the parser text similar to how we parse the input stream or a string using XMLPullParser

Here is a sample code to parse from resource xml

 try {
        XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.data);

        int eventType = xmlResourceParser.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 " + xmlResourceParser.getName());
            } else if (eventType == XmlPullParser.END_TAG) {
                System.out.println("End tag " + xmlResourceParser.getName());
            } else if (eventType == XmlPullParser.TEXT) {
                System.out.println("Text " + xmlResourceParser.getText());
            }
            eventType = xmlResourceParser.next();
        }
        System.out.println("End document");
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


来源:https://stackoverflow.com/questions/23175773/android-parse-using-xmlpullparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!