Java XML – JDOM2 – Namespaces

JDOM2 handles namespaces very well. However, there are three areas where confusion may arise while using namespaces. In this tutorial we look at them.

Creating new elements

While creating new elements in JDOM2, it is possible to pass the namespace to which the element should belong. However, the namespace only applies to the Element and not its children. i.e. the namespace assignment does not cascade. Here’s an example

The output is

Notice how the namespace prefix is applied only to only child.

Searching for a child which is in a namespace

In the next example we read the XML created in the example above. (test.xml) we then search for a child named ‘child1’, first without specifying a namespace and then after specifying a namespace. In the first case it is not able to find the child, in the second case it does

XPath and Namespace

JDOM2 XPath allows searching for an element with a specific Namespace. If an element is specified in a new Namespace then pass that JDOM2 Namespace object when searching for that element. If the XML defines a new default Namespace then create a new ‘dummy’ JDOM2 Namespace object with any prefix and the default Namespace URI specified in the XML. Access elements in the XML using the prefix of the ‘dummy’ JDOM2 Namespace object. . See example for more details. The example uses the following xml

The Example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top