Quick revision
The short answer
We extend DefaultHandler, start a StringBuilder in startElement when we meet <amount>, append text in characters(), and in endElement parse the buffer and add it to the sum; we count an order in endElement for <order>. The pitfall is that characters() may be called several times for one piece of text, with the text split at any point, so we must always append to a buffer and only use it in endElement.
What to remember
In this answer, we wrote a SAX handler that extends DefaultHandler, starts a StringBuilder when it enters <amount>, appends in characters(), adds the parsed value to a BigDecimal sum in endElement() and counts orders in endElement() for <order>. We saw that characters() can deliver one text node in several pieces, so parsing inside it gives wrong totals at random places; we always buffer and read in endElement(). We created the parser with SAXParserFactory with DTDs disallowed, and with namespace awareness enabled we matched on uri and localName rather than qName. SAX pushes events at us, so the handler owns all the state.
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.
We extend DefaultHandler, start a StringBuilder in startElement when we meet <amount>, append text in characters(), and in endElement parse the buffer and add it to the sum; we count an order in endElement for <order>. The pitfall is that characters() may be called several times for one piece of text, with the text split at any point, so we must always append to a buffer and only use it in endElement.
Background to this question
SAX is the oldest streaming XML API in Java, and a lot of production code still uses it for large files. This question checks two things: whether we can write a correct handler, which means keeping our own state, and whether we know the one callback that trips almost everybody up. In this answer, we will recap how SAX delivers a document, write the handler step by step, see the characters() bug in action, run the parser with safe settings, and finish with the namespace-aware variant.
1A Quick Recap of How SAX Works
SAX, the Simple API for XML, is push-based. We do not ask the parser for the next piece of the document; instead the parser reads the file and calls methods on a handler object we give it. It calls startElement() when it sees an opening tag, characters() when it sees text, and endElement() when it sees a closing tag. DefaultHandler is a convenience class that implements all these callbacks with empty bodies, so we only override the ones we need.
Because the parser drives everything and forgets each event as soon as our method returns, SAX never builds a tree, which is why its memory use stays tiny. The price is that the handler must remember whatever context it needs, such as whether we are currently inside an <amount> element. Keeping that state is our job.
11 messages in order. Play them, or step through them one at a time.
The text 12.50 may arrive in two calls; the handler joins them before using it.
2Writing the Handler
Here is the full handler. It uses BigDecimal for the sum, because amounts are money and double would introduce rounding errors.
Notice three decisions. We create the buffer only when we enter <amount>, so whitespace and text from other elements are ignored. We use the text only in endElement(), when we know it is complete. And we count orders in endElement() for <order>, so an order is counted once it has been fully read; counting in startElement() would also work for a simple count, but endElement() is the natural place if we later need the order's total.
3The characters() Pitfall
The tempting version parses the text directly inside characters(), like this. It works on small test files and then produces wrong totals in production.
The SAX contract says a parser may deliver one run of text in any number of characters() calls. In practice this happens when the text crosses the parser's internal buffer boundary, which for a big file is every few kilobytes, and around entity references and CDATA sections. So the bug appears at random places in large files, and a 200-line test file almost never reveals it. The rule is simple: characters() only appends to a buffer, and the buffer is read in endElement().
4Running the Parser Safely
SAXParserFactory creates the parser. Before using it on files we did not write ourselves, we turn off DTDs, which shuts the door on XML external entity attacks.
The handler object holds the results after parse() returns, so we simply read its getters. A handler is stateful, so we create a new one for every file and never share one between threads.
5Namespace-Aware Parsing
SAXParserFactory is not namespace-aware by default. In that mode qName holds the name as written, prefix included, and localName may be empty. If the file uses namespaces, for example <o:amount xmlns:o="urn:orders">, matching on qName would depend on the prefix the partner chose, which can change at any time. So we enable namespaces and match on uri and localName instead.
The namespace URI is the real identity of an element; the prefix is only a local abbreviation. Matching on uri and localName makes the handler correct whatever prefix the file uses.
6Follow-up questions
Why not use a boolean flag instead of setting the StringBuilder to null?
A boolean flag plus a buffer that we clear works just as well. Using the buffer itself as the flag removes one field and one way to forget to reset state, but it is a matter of style. What matters is that state is set on start, used on end and reset afterwards.
What happens to whitespace between elements?
The parser reports it through characters() as well (or ignorableWhitespace() when a DTD says it is ignorable). Because our buffer only exists while we are inside <amount>, that whitespace is ignored automatically. A handler that appends everything to one shared buffer would collect it and must strip or reset carefully.
How do we report the line of a bad amount?
Override setDocumentLocator(Locator) and keep the Locator. In endElement() we can call locator.getLineNumber() and include it in the exception or the error log, which makes bad partner files much easier to fix.
7Conclusion
In this answer, we wrote a SAX handler that extends DefaultHandler, starts a StringBuilder when it enters <amount>, appends in characters(), adds the parsed value to a BigDecimal sum in endElement() and counts orders in endElement() for <order>. We saw that characters() can deliver one text node in several pieces, so parsing inside it gives wrong totals at random places; we always buffer and read in endElement(). We created the parser with SAXParserFactory with DTDs disallowed, and with namespace awareness enabled we matched on uri and localName rather than qName. SAX pushes events at us, so the handler owns all the state.
Open with
I would extend DefaultHandler and keep three fields: an order count, a BigDecimal sum, and a StringBuilder that is only non-null while I am inside an amount element.
Then, if they want more
In startElement, when the name is amount, I create the builder. In characters, if the builder exists, I append the chars. In endElement, for amount I parse the builder's content, add it to the sum and set the builder back to null; for order I increment the count.
Then I create the parser with SAXParserFactory, turn on disallow-doctype-decl so no DTD and no external entities are processed, and call newSAXParser().parse with the input stream and my handler, and read the results from the handler afterwards.
The pitfall is characters: the parser is allowed to split one text node into several calls, typically at its buffer boundaries or around entities, so 12.50 may arrive as 12 dot and 50. If you parse inside characters you get wrong totals or NumberFormatExceptions at random places in big files, which tests rarely catch.
So characters only appends, and endElement uses the text. If the document uses namespaces, I enable namespace awareness and match on uri and localName instead of qName, because the prefix is not stable. And since SAX pushes events, all context is state in my handler, one handler per file.
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 "Write a SAX handler that counts <order> elements and sums the text of their <amount>...": https://scrivio-interview-library.netlify.app/java/xml-processing/e9ef710bc0/