Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml pull parser assets xml

How can i parse a local XML file in the assets folder using pull parser? I can't get pull parser to work. It always throws an io exception. I think I can't get the path to the file, or connecting to the file.

like image 352
mixm Avatar asked May 23 '10 20:05

mixm


1 Answers

mixm,

I was toying with various ways to load a local file from both 'assets' and 'res', but to answer your question as asked (as no one else seems to have):

First, either make sure your XML is valid before testing or turn off validation, this is how you can do that and instantiate a pull parser at the same time:

    try {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setValidating(false);
        XmlPullParser myxml = factory.newPullParser();

Then open the xml file and set as input to your pull parser:

        InputStream raw = getApplicationContext().getAssets().open("simple.xml");
        myxml.setInput(raw, null);

Now setup your pull loop (or other, depends on whether you want to do deferred pulling or not, that's your design decisions:

        int eventType = myxml.getEventType();
        while(eventType != XmlPullParser.END_DOCUMENT) {
            if(eventType == XmlPullParser.START_DOCUMENT) {

                Log.d(MY_DEBUG_TAG, "In start document");
            }
            else if(eventType == XmlPullParser.START_TAG) {
                Log.d(MY_DEBUG_TAG, "In start tag = "+myxml.getName());
            }
            else if(eventType == XmlPullParser.END_TAG) {
                Log.d(MY_DEBUG_TAG, "In end tag = "+myxml.getName());

            }
            else if(eventType == XmlPullParser.TEXT) {
                Log.d(MY_DEBUG_TAG, "Have text = "+myxml.getText());
            }
            eventType = myxml.next();
        }
    } catch (XmlPullParserException e) {

Note the myxml.getEventType() , you need to do this to get the parse going and handle what type events you are pulling. Note: catch blocks omitted for readability.

Tested the above on 2.1, hope it helps -Frank

like image 99
Frank C. Avatar answered Oct 15 '22 17:10

Frank C.