开发者

Abort SAX parsing mid-document?

开发者 https://www.devze.com 2022-12-25 22:56 出处:网络
I\'m parsing a very simple XML schema with a SAX parser in Android. An example file would be <Lists>

I'm parsing a very simple XML schema with a SAX parser in Android.

An example file would be

<Lists>
<List name="foo">
<Note title="note 1" .../>
<Note title="note 2" .../>
</List>
<List name="bar">
<Note title="note 3" .../>
</List>
</Lists>

The ... represents more note data as attributes that aren't important to question.

I use a SAX parser to parse the document and only implement the startElement and 'endElement' methods of the HandlerBase to handle Note and List nodes.

However, In some cases the files can be very large and take some time to process. I'd like to be able to abort the parsing process at any time (i.e. user presses cancel button).

The best way I've come up with is to throw an exception from my startElement method when certain conditions are met (i.e. boolean stopParsing is true).

Is there a better way to do this?

I've always used DOM style parsers, so I don't fully understand the SAX parser.

One final note, I'm running this on Android, so I will have the Parser running on a worker thread开发者_运维技巧 to keep the UI responsive. If you know how I can kill the thread safely while the parser is running that would answer my question as well.


You might want to look into XMLPullParser as this could be performed easily by just not calling the next method. You are in more control over the parsing.

XmlPullParser xpp=getResources().getXml(R.xml.lists);
while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
    if (xpp.getEventType()==XmlPullParser.START_TAG) {
        if (xpp.getName().equals("list")) {
            items.add(xpp.getAttributeValue(0));
        }
    }

    xpp.next();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消