Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop parsing xml document with SAX at any time?

Tags:

java

xml

sax

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

like image 418
Diablo.Wu Avatar asked Aug 28 '09 06:08

Diablo.Wu


People also ask

How SAX is an alternative method for parsing XML document?

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.

What are the limitations of SAX in XML?

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.

How is XML passing done with SAX?

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.

What is SAX parser exception?

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.


2 Answers

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();     }     ... } 
like image 194
Tom Avatar answered Oct 22 '22 13:10

Tom


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).

like image 33
McDowell Avatar answered Oct 22 '22 12:10

McDowell