Java. Sax parser. How to manually break parsing? [duplicate]
Asked Answered
W

3

9

Tell me please is it possible to break the process of parsing? I.e. exit this loop not reaching the end of document and corresponding event "endDocument" ?

Wellesley answered 3/6, 2010 at 8:27 Comment(1)
Same as this question #1345793Monophagous
U
13

Throw an exception in the handler and catch it in the code block where you started parsing:

try {
    ...
    xmlReader.parse();
} catch (SAXException e) {
    if (e.Cause instanceof BreakParsingException) {
        // we have broken the parsing process
        ....
    }
}

And in your DocumentHandler:

public void startElement(String namespaceURI,
                     String localName,
                     String qName,
                     Attributes atts)
              throws SAXException {
    // ...
    throw new SAXException(new BreakParsingException());
}
Unconditioned answered 3/6, 2010 at 8:29 Comment(2)
BTW: 2 years later I am starting to think that it is pretty unfortunate that we have to use an exception to control the flow. Breaking the parse process can be perfectly valid in non-error scenarios... If ever anybody finds a better solution I would be happy to read it!Unconditioned
Throw a subclass of SAXParseException and you'll get a callback in the ErrorHandler.Inclinable
N
4

Simple solution would be to use StAX parsing - instead of SAX. While SAX has push parsing - events are sent to the Handler by the Parsers, StAX is pull parsing, events are given to us through XMLEventReader which can be used similar to an iterator. So, it is easier to implement conditional break to break out of the parsing.

Nectarous answered 23/10, 2012 at 22:41 Comment(0)
H
2

You have to throw a SAXException. In order to distiguish it from regular errors I would subclass it with my own Exception class

Hurl answered 3/6, 2010 at 8:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.