views:

196

answers:

1

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.

+1  A: 

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();
}
Steve
That looks good. The only thing I have to figure out now is how to stop it within a worker thread.
CodeFusionMobile