Quick revision
The short answer
For new code I would normally choose StAX, because our code pulls events and can keep state in local variables and simply stop reading. I would still choose SAX when the component plugs into an existing pipeline of SAX handlers and XMLFilterImpl filters, or into libraries that consume or produce SAX events, such as some XSLT and validation APIs. SAX has no stop call, so to stop early we throw our own SAXException subclass from the handler and catch it around parse().
What to remember
In this answer, we saw that SAX pushes events into handler callbacks while StAX lets our loop pull them, so StAX keeps state in local variables and is usually easier for new code. SAX remains a good fit when the component joins an existing chain of handlers and XMLFilterImpl filters, or feeds SAX-based XSLT and validation APIs. To stop SAX early we throw a dedicated SAXException subclass and catch only that around parse(), while in StAX we simply break and close. Both stream with low memory, the speed difference rarely matters, and both work with XSD validation through SchemaFactory and Validator.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For new code I would normally choose StAX, because our code pulls events and can keep state in local variables and simply stop reading. I would still choose SAX when the component plugs into an existing pipeline of SAX handlers and XMLFilterImpl filters, or into libraries that consume or produce SAX events, such as some XSLT and validation APIs. SAX has no stop call, so to stop early we throw our own SAXException subclass from the handler and catch it around parse().
Why this question is asked
Both SAX and StAX are streaming parsers that keep memory low, so the choice between them is not about memory. It is about who controls the loop, how the code reads, and what it must connect to. Interviewers ask this to see whether we can make that judgment and whether we know the awkward corner of SAX, stopping in the middle of a document. In this answer, we will compare the two programming models, look at the cases where SAX is still the better fit, show the exception trick for stopping early and the much simpler StAX version, and touch on performance and XSD validation.
1A Quick Recap: Push Versus Pull
SAX is push-based. We call parse() once and the parser drives the whole document, calling our handler's startElement(), characters() and endElement() methods. Our code is a set of callbacks, and any context, such as which element we are inside, lives in fields of the handler.
StAX, the Streaming API for XML, is pull-based. We create an XMLStreamReader and call next() in our own loop, asking for one event at a time. Because we own the loop, context can live in local variables, we can call helper methods that read a subtree, and we can stop whenever we like by simply leaving the loop.
| Aspect | SAX | StAX |
|---|---|---|
| Who drives | the parser calls our handler | our loop calls next() |
| Where state lives | fields of the handler | local variables and the call stack |
| Stopping early | throw an exception from a callback | break out of the loop and close |
| Writing XML | not part of the API | XMLStreamWriter |
| Chaining components | XMLFilterImpl, ContentHandler pipelines | possible, but less standard |
| Memory | small buffer | small buffer |
2When SAX Is Still the Better Choice
The strongest reason to pick SAX today is integration. A lot of the XML ecosystem speaks SAX events. An XMLFilterImpl sits between the parser and the next handler and can rename elements, drop attributes or count records, and several filters can be chained into a pipeline. The JDK's XSLT support can take a SAXSource as input and can produce SAX events through SAXResult or a TransformerHandler, and a ValidatorHandler from javax.xml.validation validates a stream of SAX events. If our new component must plug into an existing chain of handlers, writing it as another SAX ContentHandler is the natural fit, and converting the pipeline to StAX would cost more than it saves.
A second reason is the team: if the code base already has many well-tested SAX handlers, a new one in the same style is easier to review than a lone StAX class. Outside those cases, StAX code is usually shorter, has fewer state flags and is easier to read, because the order of the code follows the order of the document.
3Stopping Early in SAX
Suppose we need only the header of a 3 GB file, for example the <batchId> at the top, and want to stop as soon as we have it. SAX has no method to stop the parser cleanly. The accepted way is to throw an exception from the handler. We define our own subclass of SAXException so that we can tell our intentional stop apart from a real parse error.
Notice that we catch only StopParsing. A genuine SAXParseException from a malformed file still propagates, so we do not hide real errors. We also make sure the input stream is closed afterwards, for example with try-with-resources around it, because the parser stopped in the middle and we own the stream.
4The Same Thing in StAX
With StAX the early stop needs no trick at all, which is a good illustration of why pull parsing is pleasant for new code.
The control flow is plain Java: a loop and a break. There is no extra exception class and no state field to communicate the result.
5Performance and Validation
Both APIs read the file once with a small buffer, so their memory use is similar and low. Measured raw speed can differ slightly depending on the implementation; SAX is sometimes a little faster with the built-in JDK parser, and alternative StAX implementations such as Woodstox or Aalto are very fast. In real jobs the cost of what we do with each record, such as database writes, usually dwarfs the parsing difference, so speed rarely decides the choice.
XSD validation is available to both. We build a Schema with SchemaFactory and then either call a Validator with a SAXSource or a StAXSource, or attach the schema to the parser factory with setSchema() so that the parser validates while it reads. With either API we should configure the SchemaFactory and Validator securely too, for example by restricting ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA, because each XML API in the JDK has its own settings.
6Follow-up questions
Is throwing an exception to stop SAX expensive?
It happens once per file, so the cost is negligible. We can make it even cheaper by not filling the stack trace, but readability matters more. The important part is a dedicated exception type so the catch block cannot swallow real parse errors.
Can a SAX filter be written with StAX instead?
Yes, StAX has EventFilter and StreamFilter, and we can write an XMLEventReader that wraps another one. They work well within StAX code, but the wider ecosystem of transformers and validators connects most naturally through SAX ContentHandler and XMLFilter, so for pipelines SAX remains the common language.
Does StAX support writing as well as reading?
Yes. XMLStreamWriter and XMLEventWriter write XML in a streaming way, with escaping handled for us. SAX itself has no writing API; to produce XML from SAX events we connect them to a TransformerHandler, which is more ceremony.
7Conclusion
In this answer, we saw that SAX pushes events into handler callbacks while StAX lets our loop pull them, so StAX keeps state in local variables and is usually easier for new code. SAX remains a good fit when the component joins an existing chain of handlers and XMLFilterImpl filters, or feeds SAX-based XSLT and validation APIs. To stop SAX early we throw a dedicated SAXException subclass and catch only that around parse(), while in StAX we simply break and close. Both stream with low memory, the speed difference rarely matters, and both work with XSD validation through SchemaFactory and Validator.
Open with
For a brand-new component my default is StAX. With StAX my own loop pulls events, so state is in local variables, I can call a helper that reads one subtree, and I can stop by breaking out of the loop.
Then, if they want more
With SAX the parser pushes callbacks at me, so every bit of context becomes a field in the handler, which gets hard to follow as the format grows.
I would still pick SAX when the component has to fit into an existing SAX pipeline, for example a chain of XMLFilterImpl filters, or when it feeds something that consumes SAX events, like a TransformerHandler for XSLT or a ValidatorHandler. Then writing another ContentHandler is the natural fit.
Stopping early is the awkward part of SAX: there is no stop method, so I define my own subclass of SAXException, throw it from the callback once I have what I need, and catch exactly that type around parse, so real parse errors still surface, and I close the stream myself.
Memory is low with both, and SAX may be slightly faster in some benchmarks, but the record processing usually costs far more than parsing. XSD validation works with both through SchemaFactory, either a Validator or setSchema on the parser factory, configured securely.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "When would you still choose SAX over StAX for a new Java component, and how do you stop...": https://scrivio-interview-library.netlify.app/java/xml-processing/4a9262bfdc/