Gotcha!

DOM has a set of troublesome spots just like SAX, and just like the APIs we’ll cover in the next few chapters. I will point some of those out to you, and hopefully save you a few hours of debugging time along the way. Enjoy; these happen to be problems that I’ve run into and struggled against for quite a while before getting things figured out.

The Dreaded WRONG DOCUMENT Exception

The number one problem that I see among DOM developers is what I refer to as “the dreaded WRONG DOCUMENT exception.” This exception occurs when you try to mix nodes from different documents. It most often shows up when you try to move a node from one document to another, which turns out to be a common task.

The problem arises because of the factory approach I mentioned earlier. Because each element, attribute, processing instruction, and so on is created from a Document instance, it is not safe to assume that those nodes are compatible with other Document instances; two instances of Document may be from different vendors with different supported features, and trying to mix and match nodes from one with nodes from the other can result in implementation-dependent problems. As a result, to use a node from a different document requires passing that node into the target document’s insertNode( ) method. The result of this method is a new Node, which is compatible with the target document. In other words, this code is going to cause problems:

Element otherDocElement = otherDoc.getDocumentElement( ); ...

Get Java and XML, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.