Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

Code iterates doc.getDocumentElement().getChildNodes() and casts every node to Element, failing with ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element. Why?

getChildNodes() returns every kind of child node, not only elements. In a pretty-printed file the line breaks and spaces between two elements are text nodes, so the loop meets a DeferredTextImpl (the JDK's internal text node class) and the cast to Element fails. The fix is to check node.getNodeType() == Node.ELEMENT_NODE before casting, or to select only elements with getElementsByTagName() or XPath.

Why this question is asked

This bug is a classic because the code looks obviously right and often passes its tests. The test file is written on one line, the production file is formatted by a partner's tool, and suddenly a ClassCastException appears in code that nobody changed. Interviewers ask it to see whether we understand the DOM model itself rather than only its method names. In this answer, we will recap what a node is in DOM, reproduce the exception, see exactly where the hidden text nodes come from, look at the safe ways to walk elements, and explain why the tempting setIgnoringElementContentWhitespace() switch usually does nothing.

1A Quick Recap of Nodes and Elements in DOM

DOM, the Document Object Model, is the W3C API that turns a whole XML file into a tree of objects in memory. Every object in that tree is a Node. Element is only one kind of Node. Others are Text for character data, Comment for comments, ProcessingInstruction for lines such as <?xml-stylesheet ...?>, CDATASection, and Attr for attributes.

Every Node reports its kind through getNodeType(), which returns a short constant such as Node.ELEMENT_NODE (1), Node.TEXT_NODE (3) or Node.COMMENT_NODE (8). The JDK's built-in parser is a copy of Apache Xerces, and by default it builds a deferred DOM, which creates the real node objects lazily. That is why the class in the error message is com.sun.org.apache.xerces.internal.dom.DeferredTextImpl: it is simply the JDK's Text node.

The key fact is that getChildNodes() returns a NodeList of all child nodes, whatever their type. It does not filter anything for us.

2Reproducing the Exception

Let us parse a small file that has been formatted with line breaks and indentation, exactly the way a person or an editor would write it.

Java
String xml = """
<orders>
<order id="1"/>
<!-- second order follows -->
<order id="2"/>
</orders>
""";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml.strip())));
NodeList kids = doc.getDocumentElement().getChildNodes();
System.out.println(kids.getLength()); // 7, not 2
for (int i = 0; i < kids.getLength(); i++) {
Node n = kids.item(i);
System.out.println(n.getNodeType() + " " + n.getNodeName());
}
// 3 #text (newline and spaces before the first order)
// 1 order
// 3 #text
// 8 #comment
// 3 #text
// 1 order
// 3 #text (newline before </orders>)
Element first = (Element) kids.item(0); // ClassCastException: DeferredTextImpl cannot be cast to Element
Children of <orders> in the formatted file
IndexNode typeContent
0TEXT_NODE (3)newline and two spaces
1ELEMENT_NODE (1)<order id="1"/>
2TEXT_NODE (3)newline and two spaces
3COMMENT_NODE (8)second order follows
4TEXT_NODE (3)newline and two spaces
5ELEMENT_NODE (1)<order id="2"/>
6TEXT_NODE (3)newline before </orders>
Only two of the seven children are elements; the cast fails on index 0.

Notice the count: two orders, but seven children. Between every pair of tags there is a newline and some spaces, and XML says that this is character data like any other. The parser has no way to know that we consider it formatting, so it keeps it as a text node. The comment is a child too. Our loop assumed that every child is an element, and the very first child proved it wrong.

3Why the Tests Passed and Production Failed

If the test file is written as <orders><order id="1"/><order id="2"/></orders> on a single line, there is no character data between the tags, so getChildNodes() returns exactly two elements and the cast always succeeds. The code is wrong in both cases, but only the pretty-printed file exposes it.

So when we see this exception, the first question to ask is: what does the real input look like? Pretty-printed XML is by far the most common trigger, followed by comments and processing instructions that a partner added later. A good habit is to keep at least one formatted, commented sample file in the test resources for every XML format we read.

4Fix 1: Check the Node Type Before Casting

The direct fix keeps the loop but skips anything that is not an element.

Java
NodeList kids = doc.getDocumentElement().getChildNodes();
List<Element> orders = new ArrayList<>();
for (int i = 0; i < kids.getLength(); i++) {
Node n = kids.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) { // skips text, comments, PIs
orders.add((Element) n);
}
}
System.out.println(orders.size()); // 2
System.out.println(orders.get(1).getAttribute("id")); // 2

This is the right choice when we really want the direct children in document order, whatever their names. With Java 16 and later we can write the check as if (n instanceof Element e), which tests and casts in one step and reads more naturally.

5Fix 2: Ask Only for the Elements We Want

Often we do not care about every child, only about the order elements. Then we can let DOM or XPath do the selection.

Java
NodeList byName = doc.getDocumentElement().getElementsByTagName("order");
System.out.println(byName.getLength()); // 2, only elements are returned
XPath xp = XPathFactory.newInstance().newXPath();
NodeList byPath = (NodeList) xp.evaluate("/orders/order", doc, XPathConstants.NODESET);
System.out.println(byPath.getLength()); // 2

There is one difference to keep in mind. getElementsByTagName() searches all descendants, not only direct children, so a nested <order> inside another element would also be returned. The XPath /orders/order selects direct children only. We choose the one that matches what the business data means.

6Why setIgnoringElementContentWhitespace() Usually Does Nothing

DocumentBuilderFactory has a method with a very promising name: setIgnoringElementContentWhitespace(true). Many developers try it, see no change, and are confused. The reason is that the parser can only drop whitespace that it knows is ignorable, and it only knows that from a grammar. If a DTD (or a schema used for validation) declares that <orders> contains only <order> elements, then whitespace between them cannot be data, and the parser can drop it. Without a DTD, the parser must assume the whitespace might matter, so it keeps it.

Since most modern files have no DTD, and we usually disable DTDs anyway for security reasons, this switch is not a fix we can rely on. Checking the node type, or selecting elements explicitly, works for every input.

7Follow-up questions

Does getFirstChild() have the same problem?

Yes. getFirstChild(), getLastChild(), getNextSibling() and getPreviousSibling() all walk over every node type, so in a formatted file getFirstChild() of <orders> is usually a whitespace text node. If we navigate by siblings, we need a small helper that skips forward until it finds a node whose type is ELEMENT_NODE.

Should I strip whitespace text nodes after parsing?

We can, for example with an XPath //text()[normalize-space()=''] and removing each result, and it is sometimes useful before re-serialising a document. But it changes the data for every reader of the tree and costs a full pass, so for reading code it is simpler and safer to write loops that ignore non-element nodes.

Why is the class called DeferredTextImpl and not just Text?

Text is the interface from the org.w3c.dom package. The JDK ships an internal copy of Apache Xerces, and its default deferred DOM implementation creates node objects lazily from compact internal arrays; DeferredTextImpl is its implementation of Text. We should always program against the interfaces and never import the internal com.sun classes.

8Conclusion

In this answer, we saw that getChildNodes() returns all child nodes, including the whitespace text between elements, comments and processing instructions, so casting every child to Element breaks on the first formatted file. Compact test files hide the bug, pretty-printed production files expose it. We fix it by checking getNodeType() == Node.ELEMENT_NODE (or instanceof Element) before casting, or by selecting elements with getElementsByTagName() or XPath, and we do not rely on setIgnoringElementContentWhitespace(), which only works when a DTD or schema tells the parser which whitespace is ignorable.

What to say in the interviewAbout 80 seconds aloud

Open with

The cast fails because getChildNodes returns every kind of node, not only elements. In a pretty-printed file, the newline and indentation between two tags is character data, so the parser keeps it as a text node, and the JDK's Xerces copy represents it as DeferredTextImpl.

Then, if they want more

Comments and processing instructions are children too. So the first child of the root is usually whitespace, and casting it to Element throws. That also explains why it often passes tests: if the test XML is on one line, there are no text nodes between the tags and every child happens to be an element.

The fix is to check getNodeType equals Node.ELEMENT_NODE, or use instanceof Element, before casting. If I only want certain elements, I select them directly with getElementsByTagName, keeping in mind that it searches all descendants, or with an XPath like /orders/order for direct children.

I would not rely on setIgnoringElementContentWhitespace, because the parser can only drop whitespace it knows is ignorable, which requires a DTD or schema, and we usually have neither. I would also add a formatted, commented sample file to the tests so this cannot come back.

About this answer

Last updated
12 November 2026
Versions it names
Java 16
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 "Code iterates doc.getDocumentElement().getChildNodes() and casts every node to Element...": https://scrivio-interview-library.netlify.app/java/xml-processing/1fd7a8f786/