Namespaces in JDOM

Hi,

I have a problem with namespaces in JDOM. To me it looks like a JDOM bug, but I’m not sure. Maybe I can workaround it on my side.

I need to add a namespace to my root element. This namespace should never occur anywhere else in the document.

See the following piece of code.


public static void main( String[] args ) throws Throwable
{
    org.jdom.Document doc = new org.jdom.Document();
    
    Element e0 = new Element( "e0" );
    e0.setNamespace( org.jdom.Namespace.getNamespace( "http://bla" ) );
    //e0.setNamespace( org.jdom.Namespace.getNamespace( "testns", "http://bla" ) );
    
    Element e1 = new Element( "e1" );
    e0.addContent( e1 );
    Element e2 = new Element( "e2" );
    Element e3 = new Element( "e3" );
    e2.addContent( e3 );
    e0.addContent( e2 );
    
    doc.addContent( e0 );
    
    XMLOutputter outp = new XMLOutputter();
    outp.setFormat( Format.getPrettyFormat() );
    FileOutputStream fos = new FileOutputStream( "test.xml" );
    outp.output( doc, fos );
    fos.close();
}

This results in the following XML.


<?xml version="1.0" encoding="UTF-8"?>
<e0 xmlns="http://bla">
  <e1 xmlns="" />
  <e2 xmlns="">
    <e3 />
  </e2>
</e0>

Note the empty xmlns attributes for e1 and e2 and no such attribute for e3. Neither e1 nor e2 nor e3 should have such an attribute.

If I change the code and swap the commonted lines
e0.setNamespace( org.jdom.Namespace.getNamespace( “testns”, “http://bla” ) );
to use this, I get the following XML.


<?xml version="1.0" encoding="UTF-8"?>
<testns:e0 xmlns:testns="http://bla">
  <e1 />
  <e2>
    <e3 />
  </e2>
</testns:e0>

The empty xmlns attributes are gone. But the namespace has a prefix now, but I cannot use a prefix at that place.

Is this a bug in JDOM or can I do somethign about it?

Marvin

I found the solution.

You have to add the same namespace to all the children and grandchildren of the e0 element until there is an element with a different namespace. Then JDOM will not add a namespace attribute to them.

It still looks like a bug or at least a lack of functionality, that I cannot make JDOM inherit the parent namespace automatically (change default behavior). Or I’m just blind.

Thanks anyway guys.

Marvin