Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Use XMLStreamReader to read a huge file of <customer id=".."><name>..</name></customer> records and pass each as a Customer record to a consumer without loading the whole file.

We create an XMLInputFactory with DTDs and external entities disabled, loop over events with XMLStreamReader, read the id attribute on the start of each <customer>, read the name with getElementText(), and on the end of <customer> build a Customer record and pass it to the consumer. Because each record is handed on and forgotten, memory stays proportional to one record, not to the file.

Background to this question

Reading a huge file record by record is the most common real use of StAX, so this is a very practical coding question. A good answer shows a correct event loop, safe factory settings, proper resource handling and an understanding of what the cursor is doing at each step. In this answer, we will recap the StAX cursor model, configure the factory securely, write the reader method, walk through the events for one record, handle closing correctly, and then answer the follow-up about skipping subtrees we do not need.

1A Quick Recap of the StAX Cursor

StAX, the Streaming API for XML in javax.xml.stream, gives us XMLStreamReader, a cursor over the document. Calling next() moves the cursor to the next event and returns its type as an int, such as START_ELEMENT, CHARACTERS or END_ELEMENT. While the cursor is on an event, we can ask about it: getLocalName() for the element name, getAttributeValue() for an attribute, getText() for text.

Nothing is kept once the cursor moves on. That is what makes StAX streaming: the parser only holds a small buffer, and our code decides what is worth remembering. Here we will remember the fields of the current customer, and nothing else.

2Creating the Factory Safely

Before reading any file that comes from outside, we switch off DTD processing and external entities, so that a malicious document cannot make the parser read local files or call internal URLs.

Java
XMLInputFactory f = XMLInputFactory.newFactory();
f.setProperty(XMLInputFactory.SUPPORT_DTD, false);
f.setProperty("javax.xml.stream.isSupportingExternalEntities", false); // same as IS_SUPPORTING_EXTERNAL_ENTITIES

The factory is relatively expensive to create and safe to share once configured, so in a real service we create it once and keep it in a field. The readers it creates are not thread-safe; each file gets its own reader.

3Writing the Reader

Here is the complete method. Customer is a record, record Customer(String id, String name) {}, and the consumer is whatever processes customers: a database writer, a Kafka producer or a test list.

Java
record Customer(String id, String name) {}
static void readCustomers(Path file, XMLInputFactory f, Consumer<Customer> consumer)
throws IOException, XMLStreamException {
try (InputStream in = new BufferedInputStream(Files.newInputStream(file))) {
XMLStreamReader r = f.createXMLStreamReader(in);
try {
String id = null;
String name = null;
while (r.hasNext()) {
int e = r.next();
if (e == XMLStreamConstants.START_ELEMENT) {
switch (r.getLocalName()) {
case "customer" -> { id = r.getAttributeValue(null, "id"); name = null; }
case "name" -> name = r.getElementText(); // cursor ends on </name>
default -> { }
}
} else if (e == XMLStreamConstants.END_ELEMENT && r.getLocalName().equals("customer")) {
consumer.accept(new Customer(id, name)); // hand it on, keep nothing
}
}
} finally {
r.close(); // releases the parser; does NOT close 'in'
}
} // try-with-resources closes the file stream
}
List<Customer> got = new ArrayList<>();
readCustomers(Path.of("customers.xml"), f, got::add);
System.out.println(got.get(0)); // Customer[id=c1, name=Ada Lovelace]

A few details deserve attention. getAttributeValue(null, "id") takes a namespace URI and a local name; null for the namespace means we match the attribute by local name regardless of namespace, which suits plain attributes. We reset name when a new customer starts, so a customer without a <name> gets null rather than the previous customer's name. And we call getElementText() rather than collecting CHARACTERS events ourselves, because text can arrive in several events and getElementText() joins them for us.

4Following the Events for One Record

It helps to see where the cursor is at each step for <customer id="c1"><name>Ada Lovelace</name></customer>.

Step throughCursor movements for one customer
Our loopXMLStreamReaderConsumer
next() -> START_ELEMENT customer
getAttributeValue(null, "id")
"c1"
next() -> START_ELEMENT name
getElementText()
"Ada Lovelace", cursor on END_ELEMENT name
next() -> END_ELEMENT customer
accept(Customer[c1, Ada Lovelace])

8 messages in order. Play them, or step through them one at a time.

Whitespace between tags produces CHARACTERS events, which our loop simply ignores.

Notice that getElementText() moves the cursor: it reads all text up to the matching end tag and leaves the cursor on </name>. So the next call to next() continues correctly after the name. It also throws an exception if the element contains child elements rather than only text, which is a useful check that the file has the shape we expect.

5Closing Correctly

There is a small trap in the API. XMLStreamReader has a close() method but does not implement AutoCloseable, so we cannot put it directly in a try-with-resources statement. Its close() also does not close the underlying InputStream; it only frees the parser. That is why the code uses try-with-resources for the stream and an explicit finally for the reader. If we prefer, we can wrap the reader in a tiny adapter that implements AutoCloseable and calls r.close(), and put both in one try statement.

With both closed properly, a job that reads thousands of files does not leak file handles, and memory stays proportional to one customer record however large each file is.

6Follow-up questions

How do you skip a subtree you do not care about?

Keep a depth counter. When the cursor is on the START_ELEMENT of the element to skip, say <history>, set depth to 1 and call next() repeatedly, adding 1 on every START_ELEMENT and subtracting 1 on every END_ELEMENT, until depth is 0. The cursor is then on </history> and normal processing resumes. This reads the subtree's bytes but creates nothing for them, so even a huge history section costs no memory. Some StAX implementations offer extensions for this, for example Woodstox has a skipElement() method in its extended reader interface, but the depth loop works everywhere.

Why not use XMLEventReader?

XMLEventReader returns an object for every event, which is convenient when we want to peek ahead or store events, but allocates more. For a simple record extraction like this, the cursor API is faster and the code is just as clear.

What if the file uses namespaces?

Then we compare both r.getNamespaceURI() and r.getLocalName() with the expected values, rather than relying on prefixes. The StAX factory is namespace-aware by default, so the URI is available without extra configuration.

7Conclusion

In this answer, we configured an XMLInputFactory with DTDs and external entities switched off, looped over XMLStreamReader events, took the id attribute on the start of <customer>, read the name with getElementText(), which also moves the cursor to the end of <name>, and built and passed on a Customer record at the end of each customer. We closed the reader in finally, because it is not AutoCloseable and does not close the stream, and the stream with try-with-resources. Memory stays proportional to one record, and a depth counter lets us skip whole subtrees cheaply.

What to say in the interviewAbout 80 seconds aloud

Open with

I would create the XMLInputFactory once, with SUPPORT_DTD set to false and isSupportingExternalEntities set to false, so an untrusted file cannot use entities against us. Then for each file I open a buffered input stream in try-with-resources and create an XMLStreamReader from it.

Then, if they want more

In a while hasNext loop I call next and look at the event type. On a START_ELEMENT named customer, I read the id with getAttributeValue null comma id, and reset the name. On a START_ELEMENT named name, I call getElementText, which collects all the text, even if it arrives in several chunks, and leaves the cursor on the end tag.

On the END_ELEMENT of customer, I build the Customer record and call consumer.accept, and I keep no reference to it, so memory is just one record no matter how big the file is.

One detail I always mention: XMLStreamReader has close but is not AutoCloseable, and closing it does not close the stream, so I close the reader in a finally block and let try-with-resources close the stream, or wrap the reader in a small AutoCloseable adapter.

To skip a subtree I do not need, I keep a depth counter, increment on start elements and decrement on end elements until it gets back to zero.

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 "Use XMLStreamReader to read a huge file of <customer id=".."><name>..</name></customer>...": https://scrivio-interview-library.netlify.app/java/xml-processing/86dd0c04c8/