title: Java+DOM: How do I set the base namespace of an (already created) Document?
body: <p>I am dealing with an <strong>already created</strong> Document object.
  I have to be able to set it's base namespace (attribute name "xmlns") to certain value.
  My input is DOM and is something like:</p>
  
  <pre><code>&lt;root&gt;...some content...&lt;/root&gt;
  </code></pre>
  
  <p>What I need is DOM which is something like:</p>
  
  <pre><code>&lt;root xmlns="myNamespace"&gt;...some content...&lt;/root&gt;
  </code></pre>
  
  <p>That's it. Easy, isn't it? <strong>Wrong! Not with DOM!</strong></p>
  
  <h1>I have tried the following:</h1>
  
  <h3>1) Using doc.getDocumentElement().setAttribute("xmlns","myNamespace")</h3>
  
  <p>I get a document with empty xmlns (it works on <strong>any</strong> other attribute name!)</p>
  
  <pre><code>&lt;root xmlns=""&gt;...&lt;/root&gt;
  </code></pre>
  
  <h3>2) Using renameNode(...)</h3>
  
  <p>First <strong>clone</strong> the document:</p>
  
  <pre><code>Document input = /*that external Document whose namespace I want to alter*/;
  
  DocumentBuilderFactory BUILDER_FACTORY_NS = DocumentBuilderFactory.newInstance();
  BUILDER_FACTORY_NS.setNamespaceAware(true);
  Document output = BUILDER_NS.newDocument();
  output.appendChild(output.importNode(input.getDocumentElement(), true));
  </code></pre>
  
  <p><em>I'm really missing document.clone(), but perhaps it's just me.</em></p>
  
  <p>Now <strong>rename the root node</strong>:</p>
  
  <pre><code>output.renameNode(output.getDocumentElement(),"myNamespace",
      output.getDocumentElement().getTagName());
  </code></pre>
  
  <p>Now isn't <strong>that</strong> straightforward? ;)</p>
  
  <p>What I get now is:</p>
  
  <pre><code>&lt;root xmlns="myNamespace"&gt;
      &lt;someElement xmlns=""/&gt;
      &lt;someOtherElement xmlns=""/&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>So <em>(as all of us have expected, right?)</em>, this renames the namespace <strong>only of the the root node</strong>.</p>
  
  <p><em>Curse you, DOM!</em></p>
  
  <p>Is there any way to do this recursively (without writing an own recursive method)?</p>
  
  <h3>Please help ;)</h3>
  
  <p>Please don't advice me to do some fancy workaround, such as transforming DOM to
  something else, alter the namespace there, and transform it back.
  I need DOM because it's the fastest standard way to manipulate XML.</p>
  
  <p>Note: I'm using the latest JDK.</p>
  
  <p><strong>EDIT</strong><br>
  Removed wrong assumptions from the question, which had to do with namespace <em>prefix</em>.</p>