[jdom-interest] Some background on JDOM Namespaces

Rosen, Alex arosen at silverstream.com
Tue Apr 3 07:53:12 PDT 2001

This kind of information is very helpful. Something like this should go in the
JavaDoc, I think.

A question, though. You said that "a default namespace in JDOM means nothing",
and that JDOM "does not have to keep namespace declarations". This seems wrong,
or more likely just misleading - isn't that what Namespace.getNamespace(String)
and Element.addNamespaceDeclaration(Namespace) do, respectively?

Here's the text I was thinking of for the JavaDoc. I don't know if it belongs
on Element, or on Namespace with a cross-reference from the relevent Element
methods. Any suggesions are welcome.

BTW I was thinking that changing the "prefix" parameter on
Namespace.getNamespace() to "desiredPrefix" might be clearer, no?


NOTE: An Element's Namespace represents the *logical* namespace for that
element, which may be different from the namespace *declaration* that appears
in the XML text. In particular, if an ancestor element declares a default
namespace in the XML text and the child contains no namespace declaration, the
child Element will still have that Namespace associated with it. For creation,
the child Element must be constructed with this Namespace, and for navigation,
it must be requested via getChild() using this Namespace. Similarly, if an
ancestor element declares a namespace prefix and the child uses that prefix,
the child must be requested from the parent using the local name and Namespace,
not the qualified name.

For example:

<parent xmlns="http://foo" xmlns:bar="http://bar">
  <child1 />
  <bar:child2 />

Namespace fooNS = Namespace.getNamespace("http://foo");
Namespace barNS = Namespace.getNamespace("http://bar");
Element parent = document.getChild("parent", fooNS);
Element child1 = parent.getChild("child1", fooNS);
Element child2 = parent.getChild("child2", barNS);

Note that if we were creating this tree rather than reading it, then barNS
would need to be obtained by:

Namespace barNS = Namespace.getNamespace("bar", "http://bar");

However, when we're simply navigating the tree, the Namespace prefix is

More information about the jdom-interest mailing list