Java DOM API Lessons
This document covers lessons-learned/pain-points/gotchas when dealing with the DOM API (quite possibly the world's least efficient and least helpful API).
DOM Levels
Major revs of the DOM API specification versions are referred to as "levels" and, to date, each subsequent level is a superset of the previous levels.
Specifications: Level 1, Level 2, Level 3
Namespace Support
Namespaces came around after DOM Level 1 was released. As such all the APIs and data structures dealing with namespaces were grafted on to the Level 1 API. This results in some APIs being namespace/QName aware and others not. In such cases, the APIs which are namespace aware have the suffix NS
.
Lesson: Always use the APIs that support namespaces.
Because the core data structures don't really support namespaces, this limits the type of changes you might reasonably expect to make when working with various types of DOM nodes.
Lesson: You cannot change the namespace URI that was assigned an Element/Attribute when it was created.
Lesson: Declaring namespaces by adding the appropriate attribute to an element does not make the underlying Document aware of the namespace so methods methods like Node#lookupNamespaceURI()
and Node#lookupPrefix()
won't be aware of these changes. The only way known to do this, currently, is either to create an element/attribute in the new namespace or add it to the textual serialization of the document prior to parsing it.