title: Transform XML to declare all namespaces on root element
body: <p>Is there a simple Java <del>method</del> way of "moving" all XML namespace declarations of an XML document to the root element? Due to a bug in parser implementation of an unnamed huge company, I need to programmatically rewrite our well formed and valid RPC requests in a way that the root element declares all used namespaces.</p>
  
  <p>Not OK:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;document-element xmlns="uri:ns1"&gt;
      &lt;foo&gt;
          &lt;bar xmlns="uri:ns2" xmlns:ns3="uri:ns3"&gt;
              &lt;ns3:foobar/&gt;
              &lt;ns1:sigh xmlns:ns1="uri:ns1"/&gt;
          &lt;/bar&gt;
      &lt;/foo&gt;
  &lt;/document-element&gt;
  </code></pre>
  
  <p>OK:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;document-element xmlns="uri:ns1" xmlns:ns1="uri:ns1" xmlns:ns2="uri:ns2" xmlns:ns3="uri:ns3"&gt;
      &lt;foo&gt;
          &lt;ns2:bar&gt;
              &lt;ns3:foobar/&gt;
              &lt;ns1:sigh/&gt;
          &lt;/ns2:bar&gt;
      &lt;/foo&gt;
  &lt;/document-element&gt;
  </code></pre>
  
  <p>Generic names for <del>missing</del> prefixes are acceptable. Default namespace may stay or be replaced/added as long as it is defined on the root element. I don't really mind which specific XML technology is used to achieve this (I would prefer to avoid DOM though).</p>
  
  <p>To clarify, <a href="https://stackoverflow.com/a/28119460/878469">this answer</a> refers to what I'd like to achieve as <em>redeclaring namespace declarations</em> within root element scope (entire document) on the root element. Essentially the related question is asking why oh why would anyone implement what I now need to work around.</p>