tags:

views:

828

answers:

3

I parse a big xml document with Sax, I want to stop parsing the document when some condition establish? How to do?

+8  A: 

Create a specialization of a SAXException and throw it (you don't have to create your own specialization but it means you can specifically catch it yourself and treat other SAXExceptions as actual errors).

public class MySAXTerminatorException extends SAXException {
    ...
}

public void startElement (String namespaceUri, String localName,
                           String qualifiedName, Attributes attributes)
                        throws SAXException {
    if (someConditionOrOther) {
        throw new MySAXTerminatorException();
    }
    ...
}
Tom
There any other way? not use exception.
Diablo.Wu
Why would you not want to? That's what exceptions are designed for.
Xiong Chiamiov
fwiw, that isn't what exceptions are designed for. Terminating a parse like this is not an error condition.It is however the only way to do this afaict :-(
ashirley
+1  A: 

I am not aware of a mechanism to abort SAX parsing other than the exception throwing technique outlined by Tom. An alternative is to switch to using the StAX parser (see pull vs push).

McDowell
A: 

i tried that and evey thing is ok thank you

Saeb Najim

saebnajim