Quick revision
The short answer
XMLStreamReader is a cursor: we read the details of the current event straight from the reader, so it allocates almost nothing and is the fastest option. XMLEventReader hands us an immutable XMLEvent object per event, which we can peek at, store and pass around, at the cost of an allocation for each one. To write a large file with flat memory, we use XMLStreamWriter on a buffered output stream, write each record as we produce it, flush every so often, and close it at the end; the writer escapes text and attributes for us, but namespaces and correct nesting are our responsibility.
What to remember
In this answer, we saw that XMLStreamReader is a low-allocation cursor where we read the current event from the reader, while XMLEventReader returns immutable XMLEvent objects that can be peeked at, stored and passed around at the cost of allocation. To write large files with flat memory, we streamed records from the data source into XMLStreamWriter on a buffered stream, flushed periodically and closed at the end. The writer escapes text and attributes, but we manage namespaces with setPrefix and writeNamespace and keep the document well-formed ourselves, and faster implementations such as Woodstox and Aalto drop in through the factory lookup.
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.
XMLStreamReader is a cursor: we read the details of the current event straight from the reader, so it allocates almost nothing and is the fastest option. XMLEventReader hands us an immutable XMLEvent object per event, which we can peek at, store and pass around, at the cost of an allocation for each one. To write a large file with flat memory, we use XMLStreamWriter on a buffered output stream, write each record as we produce it, flush every so often, and close it at the end; the writer escapes text and attributes for us, but namespaces and correct nesting are our responsibility.
Why this question is asked
Most StAX code reads files, but in integration work we write just as many: exports, partner feeds and reports with millions of records. Interviewers use this question to see whether we understand the two reading styles in StAX and when each is worth its cost, and whether we can produce big XML without building it in memory or by string concatenation. In this answer, we will compare the cursor and event APIs with code, write a large file with XMLStreamWriter, look at what the writer does and does not check for us, and see how faster implementations plug in.
1Two Ways to Read: Cursor and Events
StAX, the Streaming API for XML, offers two reading interfaces over the same parser. With XMLStreamReader, the reader itself represents the current position. next() moves it and returns an int event type, and we call methods like getLocalName() or getText() on the reader to learn about the current event. Nothing is created per event, so garbage is minimal.
With XMLEventReader, nextEvent() returns an XMLEvent object such as StartElement, Characters or EndElement. Each object is immutable and stays valid after the reader moves on, so we can keep it in a list, pass it to another method, or write it straight to an XMLEventWriter. peek() lets us look at the next event without consuming it, which makes some parsing logic simpler.
| Aspect | XMLStreamReader | XMLEventReader |
|---|---|---|
| Model | cursor on the current event | iterator of XMLEvent objects |
| Allocation | almost none per event | one object per event |
| Lookahead | no | peek() |
| Keep events for later | no, data is gone after next() | yes, events are immutable |
| Best for | fast bulk reading | filtering, copying, lookahead |
So the trade-off is simple. The cursor is the right default for high-volume reading, because it avoids millions of short-lived objects. The event API is worth it when we need lookahead, when we want to buffer a few events and decide later, or when we copy or filter parts of a document from a reader to a writer event by event.
2Writing a Large File With XMLStreamWriter
XMLStreamWriter is the writing counterpart of the cursor API. We call writeStartElement(), writeAttribute(), writeCharacters() and writeEndElement(), and the writer sends the bytes to the underlying stream as we go. Because nothing is kept except a small stack of open element names, we can write ten million records with the same memory as ten.
Notice that memory is flat only if the data source streams too. If orderRepository loaded every order into a List first, we would have moved the memory problem from XML to the database layer, so we use a streaming query or paging. Flushing every few thousand records keeps the writer's internal buffer small and lets downstream consumers, such as an HTTP response, start receiving data early. As with the reader, XMLStreamWriter has close() but is not AutoCloseable, and close() does not close the stream.
3What the Writer Handles and What It Leaves to Us
The writer escapes for us. writeCharacters() turns & and < into & and <, and writeAttribute() also escapes quotes, so the classic bug of string-built XML, a customer called Smith & Sons breaking the whole file, cannot happen. That alone is a strong reason never to build XML by concatenating strings.
Namespaces are a different story. By default the writer does not invent declarations. If we want <o:order xmlns:o="urn:orders">, we call setPrefix("o", "urn:orders") to tell the writer which prefix to use and writeNamespace("o", "urn:orders") to actually emit the declaration on the element, or writeDefaultNamespace() for a default namespace. Forgetting writeNamespace() produces a document that uses a prefix it never declared. The property javax.xml.stream.isRepairingNamespaces asks the writer to add missing declarations automatically, which helps, though the exact output differs between implementations.
Well-formedness is also mostly on us. The JDK writer keeps track of open elements so writeEndElement() closes the right one, but it will not stop us from writing two root elements or calling writeCharacters() after the root is closed. Some implementations, Woodstox in particular, offer optional checks for this; check your implementation's settings. In tests, we parse the output again, ideally validating it against the XSD.
4Plugging In a Faster Implementation
XMLInputFactory.newFactory() and XMLOutputFactory.newFactory() do not hard-code the JDK parser. They look for an implementation in this order: a system property such as javax.xml.stream.XMLInputFactory, the JDK configuration file, the ServiceLoader mechanism that reads META-INF/services entries from jars on the classpath, and finally the built-in default. So adding Woodstox (com.fasterxml.woodstox:woodstox-core) or Aalto to the classpath is often enough to switch implementation without changing a line of code.
Woodstox is mature and widely used, and Jackson's XML module builds on it; Aalto focuses on raw speed and also offers a non-blocking parser. When we switch, we rerun our tests and recheck security settings, because defaults such as DTD support can differ from the JDK's.
- Our code
XMLInputFactory.newFactory() - System property
javax.xml.stream.XMLInputFactory, if set - JDK configuration file
jaxp.propertiesor the stax properties file - ServiceLoaderfirst provider found on the classpath, e.g. Woodstox
- JDK defaultbuilt-in implementation
5 layers, from the top down. Step through them one at a time.
The first source that names an implementation wins; check your JDK version for the exact files.
5Follow-up questions
Can I mix the two reading styles?
Yes. XMLInputFactory.createXMLEventReader(XMLStreamReader) wraps a cursor reader in an event reader, so we can read most of a document with the fast cursor and switch to events for one tricky section. We must then use only the event reader until we are done with that section, so the two do not disagree about the position.
Is XMLEventWriter ever better than XMLStreamWriter?
When we copy or filter events from an XMLEventReader, XMLEventWriter.add(event) writes each event as it is, which makes pass-through transformations very short. For generating XML from our own data, XMLStreamWriter is more direct and allocates less.
How do you pretty-print the output of XMLStreamWriter?
The writer writes exactly what we ask for, so there is no indentation by default. We can write newline and space characters ourselves with writeCharacters(), use a small wrapping writer that indents by depth, or use an implementation option where available. For machine-to-machine files, unindented output is smaller and perfectly fine.
6Conclusion
In this answer, we saw that XMLStreamReader is a low-allocation cursor where we read the current event from the reader, while XMLEventReader returns immutable XMLEvent objects that can be peeked at, stored and passed around at the cost of allocation. To write large files with flat memory, we streamed records from the data source into XMLStreamWriter on a buffered stream, flushed periodically and closed at the end. The writer escapes text and attributes, but we manage namespaces with setPrefix and writeNamespace and keep the document well-formed ourselves, and faster implementations such as Woodstox and Aalto drop in through the factory lookup.
Open with
XMLStreamReader is a cursor. I call next, get an int event type, and read the name, attributes or text from the reader itself, so there is essentially no allocation per event and it is the fastest way to read.
Then, if they want more
XMLEventReader gives me an XMLEvent object for every event. Those objects are immutable, so I can peek at the next one, keep them in a list, or pass them to an XMLEventWriter to copy part of a document.
That flexibility costs one object per event, so I use the event API for filtering or lookahead and the cursor for bulk reading. For writing a big file, I use XMLStreamWriter on a BufferedOutputStream with UTF-8.
I write the start document and root, then loop over records coming from a streaming query, not a list, writing start elements, attributes and characters, closing each record, and calling flush every ten thousand records or so.
At the end I close the root, write end document, flush and close the writer, and close the stream separately, because the writer's close does not do that.
The writer escapes ampersands and angle brackets for me, which is why I never concatenate strings, but I have to declare namespaces myself with setPrefix and writeNamespace, or enable repairing namespaces, and make sure I do not write two roots. Implementations like Woodstox or Aalto can be dropped in through the factory's service lookup for more speed.
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 "Compare XMLStreamReader and XMLEventReader in StAX, and explain how you would write a...": https://scrivio-interview-library.netlify.app/java/xml-processing/bbdd019cf6/