0

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 Answer 1

2

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();
    }
Sign up to request clarification or add additional context in comments.

2 Comments

how to get data inside <a>xxx</a> using tag name
xmlResourceParser.getText() will return the data when eventType is TEXT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.