xml pull parser assets xml

半世苍凉 提交于 2019-12-03 09:32:34

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/2893364/xml-pull-parser-assets-xml

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