title: Write .xml in Python with pretty print and encoding declaration
body: <p>I have to create an <em>.xml</em> file that has pretty print and also the encoding declaration. It should look like this: like this: </p>
  
  <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt;
  &lt;main&gt;
      &lt;sub&gt;
          &lt;name&gt;Ana&lt;/name&gt;
          &lt;detail /&gt;
          &lt;type&gt;smart&lt;/type&gt;
      &lt;/sub&gt;
  &lt;/main&gt;
  </code></pre>
  
  <p>I know how to get the pretty print and the declaration, but not at the same time.
  To obtain the UTF-8 declaration, but no pretty print, I use the code below:</p>
  
  <pre><code>f = open(xmlPath, "w")
  et.write(f, encoding='utf-8', xml_declaration=True) 
  f.close()
  </code></pre>
  
  <p>But if I want to get the pretty print, I have to convert the xml tree into string, and I will lose the declaration. I use this code:</p>
  
  <pre><code>from xml.dom import minidom
  xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent="   ")
  with open(xmlPath, "w") as f:
      f.write(xmlstr.encode('utf-8'))
      f.close()
  </code></pre>
  
  <p>With this last code, I get the pretty print, only that the first row is:</p>
  
  <pre><code>&lt;?xml version="1.0" ?&gt;
  </code></pre>
  
  <p>I might just as well replace this with   </p>
  
  <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt;
  </code></pre>
  
  <p>but I don't find this to be the most pythonesque method.</p>
  
  <p>I use the xml module and I prefer not to install extra modules because the script has to be run from various computers with standard Python. But if it's not possible, I will install other modules.</p>
  
  <p><strong><em>Later Edit:</em></strong></p>
  
  <p>In the end, with Lenz's help, I use this:</p>
  
  <pre><code>#ET=lxml.etree
  xmlPath=os.path.join(output_folderXML ,"test.xml")
  xmlstr= ET.tostring(root, encoding='UTF-8', xml_declaration=True, pretty_print=True)
  with open(xmlPath, "w") as f:
      f.write(xmlstr)
      f.close()
  </code></pre>
  
  <p>I need to know if it is safe to write the result of the "tostring" method to the .xml file in the "w" mode, not "wb".
  As I said in one of the comments below, with "wb" I don't get the pretty print when I open the xml file in Notepad, but with "w", I do.
  Also, I have checked the xml file written in "w" mode and the special characters like "ü" are there.
  I only need an competent opinion that what I do is technically OK.</p>