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" ?
Asked
Active
Viewed 8,208 times
9
-
Same as this question http://stackoverflow.com/questions/1345293/how-to-stop-parsing-xml-document-with-sax-at-any-time – Brian Jun 03 '10 at 08:38
3 Answers
12
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());
}

chiccodoro
- 14,407
- 19
- 87
- 130
-
6BTW: 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! – chiccodoro Aug 24 '12 at 07:16
-
1Throw a subclass of [SAXParseException](http://www.saxproject.org/apidoc/org/xml/sax/SAXParseException.html) and you'll get a callback in the [ErrorHandler](http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html). – David Bullock Nov 23 '12 at 06:40
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.

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

Peter Tillemans
- 34,983
- 11
- 83
- 114