[jdom-interest] Element without a Namepace

Alex Rosen arosen at silverstream.com
Tue Jul 17 07:42:57 PDT 2001

> The root element "Identify" has several Namespaces, but it's child
> element "responseDate" was build without any namespace
> (simply Element rd = new Element("responseDate");), and so I didn't
> expect the result above.

Because you built it without any namespace, it is being output without
any namespace. Because its parent has a default namespace, XMLOutputter
needs to clear this element's namespace in order to make this happen, by
using a namespace declaration of xmlns="".

You don't want this element to have a namespace declaration, but it's
not clear if you do want it to have a namespace. If so, you need to
construct it with a Namespace object. Otherwise, it's already doing the
right thing. It's confusing at first, but it actually makes more sense
this way.

I sent this out a while ago:

Q: Why do I need to pass in a Namespace to getChild(), when the child
element I'm looking for has no namespace declaration? Specifically, for
this XML fragment:

  <y xmlns="http://foo">

I need to use code like this:

Namespace ns = Namespace.getNamespace("http://foo");
Element y = x.getChild("y", ns);
Element z = y.getChild("z", ns);

If I leave out the namespace from the second call to getChild(), it
returns null. Why?

A: JDOM works on the logical in-memory XML tree, not the textual
representation on-disk. While the element <z> has no namespace
declaration, it does have a namespace - the one inherited from its
parent, which declares a default namespace.

According to the namespaces spec, this XML fragment is identical in
meaning to the previous one:

  <y xmlns="http://foo">
    <z xmlns="http://foo" />

The way that the JDOM API handles namespaces means that you can write
code that works for both examples. Otherwise, you'd need to have code
that checked for each case separately.

Similarly, if you were constructing (instead of reading) the XML in the
first example above, you would need to write code like this:

Namespace ns = Namespace.getNamespace("http://foo");
Element y = new Element("y", ns);
Element z = new Element("z", ns);

If you left out the Namespace from the constructor of <z>, then you're
specifying that this element has no namespace, so XMLOutputter will

  <y xmlns="http://foo">
    <z xmlns="" />

More information about the jdom-interest mailing list