I parse a big xml document with Sax, I want to stop parsing the document when some condition establish? How to do?
SAX (Simple API for XML) is an event-driven algorithm for parsing XML documents. SAX is an alternative to the Document Object Model (DOM). Where the DOM reads the whole document to operate on XML, SAX parsers read XML node by node, issuing parsing events while making a step through the input stream.
SAX is not a perfect solution for all problems. For instance, it can be a bit harder to visualize compared to DOM because it is an event-driven model. SAX is not a perfect solution for all problems.
SAX: the Simple API for XML SAX is an API used to parse XML documents. It is based on events generated while reading through the document. Callback methods receive those events. A custom handler contains those callback methods.
public class SAXParseException extends SAXException. Encapsulate an XML parse error or warning. This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.
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(); } ... }
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With