JDOM and XML Parsing, Part 2
By Jason Hunter
JDOM makes XML manipulation in Java easier than ever.
In the first article of this series, I introdUCed JDOM, an open-source library for Java-optimized XML data manipulations. I eXPlained how this alternative document object model was not built on DOM or modeled after DOM but was created to be Java-specific and thereby take advantage of Java's features, including method overloading, collections, reflection, and familiar programming idioms. I covered the important classes and started examining how to use JDOM in your applications. In this article, I'll take a look at XML Namespaces, ResultSetBuilder, XSLT, and XPath.
Working with Namespaces
JDOM provides robust, native support for XML Namespaces. JDOM was created after the namespace recommendation was published, so unlike other APIs there's no pre-namespace and deprecated leftovers. (See the sidebar "XML Namespaces" for more on namespaces.) In JDOM, namespaces are represented by a Namespace class:
Namespace xHtml = Namespace.getNamespace( "xhtml", "http://www.w3.org/1999/xhtml");
During construction, an object is given a name and can optionally be given a namespace:
elt.addContent(new Element("table", xhtml));
If no namespace is given, the element is constructed in "no namespace." An element's namespace is an intrinsic part of its type, so JDOM ensures that its namespace doesn't change when it moves around the document. If an element has no namespace and moves under an element that has a namespace, it explicitly does not inherit the namespace. Sometimes that causes confusion until you learn to separate the textual representation from the semantic structure.
The XMLOutputter class sorts out the namespace issues and ensures placement of all the "xmlns" declarations into the appropriate locations, even after a document's elements have been heavily shuffled around. By default, the class places the declarations where they're first necessary. If you want them declared further up the tree (in other Words, all declarations at the root), you can use the element.addNamespaceDeclaration() method to provide that guidance.
All JDOM element or attribute Accessor methods support an optional namespace argument indicating the namespace in which to look. This example points to the xhtml namespace: