Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sax

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" ?

like image 848
Andrey Khataev Avatar asked Jun 03 '10 08:06

Andrey Khataev


3 Answers

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());
}
like image 51
chiccodoro Avatar answered Nov 13 '22 11:11

chiccodoro


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.

like image 37
Sasi Avatar answered Nov 13 '22 12:11

Sasi


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

like image 2
Peter Tillemans Avatar answered Nov 13 '22 11:11

Peter Tillemans