title: preserve namespaces with xml.etree
body: <p>When namespaces are defined in the root element of a source file, <code>lxml</code> reproduces all of them in the output. I need to do this with <code>xml.etree</code>. Even better would be to only output those that are used, but <code>xml.etree</code> does not find all of them.</p>
  
  <p>One solution is to add the namespaces forcibly with <code>root.set()</code>. However, this duplicates any namespaces that <code>xml.etree</code> does find, as shown below.</p>
  
  <p>Complete example suitable for pasting in a command prompt:</p>
  
  <pre><code>import xml.etree.ElementTree as ET
  try:
      from io import StringIO
  except ImportError:
      from StringIO import StringIO
  
  def get_namespaces(sourcestring):
      sourcefile = StringIO(sourcestring)
      return dict(
          [node for _, node in ET.iterparse(sourcefile, events=['start-ns'])])
  
  ET._namespace_map = dict()  # remove any previously registered namespaces
  sourcetext = (
      '&lt;desc xmlns="uri_a" xmlns:b="uri_b" xmlns:c="uri_c"'
      ' b:foo="c:bar"&gt;a&lt;/desc&gt;')
  source = ET.fromstring(sourcetext)
  namespaces = get_namespaces(sourcetext)
  for prefix, uri in namespaces.items():
      ET.register_namespace(prefix, uri)
      if prefix:
          tag = 'xmlns:' + prefix
      else:
          tag = 'xmlns'
      source.set(tag, uri)
  
  print(ET.tostring(source, encoding='unicode'))
  </code></pre>
  
  <p>The result, which causes my application to fail:</p>
  
  <pre><code>&lt;desc xmlns="uri_a" xmlns:b="uri_b" xmlns="uri_a" xmlns:b="uri_b" xmlns:c="uri_c" b:foo="c:bar"&gt;a&lt;/desc&gt;
  </code></pre>
  
  <p>This is similar to <a href="https://stackoverflow.com/questions/24557151/forcing-xml-etree-to-output-unused-namespaces">Forcing xml.etree to output &quot;unused&quot; namespaces</a>, but the namespaces come from a source file so they are not known by the Python code.</p>