Java Sax Parser - stop processing in EndElementListener

I'm using android's SAX parser and I wish to stop processing after I have read N elements. Some of the feeds are quite large and can take a while to churn through. How can I stop parsing if certain conditions are met in the EndElementListener for a certain element? Here is my current listener

chanItem.setEndElementListener(new EndElementListener()  {
    public void end() {
        _items.add(_item);
        if (++_currentItem == _maxElements) {
                //BREAK OUT HERE
        }
    }
});

I've tried throwing an exception within end() but EndElementListener doesn't allow for throwing any exceptions. Guidance would be much appreciated.

Answers


Define a new unchecked exception called "SaxBreakOutException":

class SaxBreakOutException extends RuntimeException {
}

Throw this in your listener:

chanItem.setEndElementListener(new EndElementListener()  {
    public void end() {
        _items.add(_item);
        if (++_currentItem == _maxElements) {
            throw new SaxBreakOutException();
        }
    }
});

And catch it in the code that calls XmLReader.parse():

reader.setContentHandler(handler);
try {
    reader.parse(new InputSource(new StringReader(xml)));
} catch (SaxBreakOutException allDone) {
}

Alternatively, switch to Android's XmlPullParser which doesn't require exceptions to break out early.


Need Your Help

Failed to load resources from resource file

.net iis

Get the following error periodically in an IIS application:

Can't access php files on local apache server

php apache apache2 hhvm

I have setup a local apache2 server, and it works and display correctly for any html files located at home/user/website, but it gives me an 404 error when i try to access php files.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.