title: Python xml.etree formatting beautify?
body: <p>I got a script that uses xml.etree.ElementTree to parse an XML-file and is supposed to add a child to an element. I have two approaches, that both work technically but both result in messed up formatting/whitespace when I dump the whole xml using ET.dump(root)</p>
  
  <p>First method I use fromstring</p>
  
  <pre><code>import xml.etree.ElementTree as ET
  
  tree = ET.parse('test.xml')
  root = tree.getroot()
  
  #snip
  
  newgroup='''
      &lt;group&gt;
          &lt;uuid&gt;%s&lt;/uuid&gt;
          &lt;id&gt;%s&lt;/id&gt;
          &lt;name&gt;%s&lt;/name&gt;
          &lt;desc&gt;%s&lt;/desc&gt;
      &lt;/group&gt;            
  ''' % (g_uuid, g_id, g_name, g_desc)
  
  access = root.find('access')
  access.append(ET.fromstring(newgroup))
  </code></pre>
  
  <p>This results in the group being added as a child, but after endtag of group is no newline and the first tag only has 1 tab, no matter how many tabulators I put into the newgroup string. </p>
  
  <pre><code>&lt;group&gt;
          &lt;uuid&gt;f60e6b30-eec9-11e6-a5d4-2c768aabceca&lt;/uuid&gt;
          &lt;id&gt;2&lt;/id&gt;
          &lt;name&gt;newgroup&lt;/name&gt;
          &lt;desc&gt;Testing groups&lt;/desc&gt;
      &lt;/group&gt;&lt;/access&gt;
  </code></pre>
  
  <p>I wonder why it takes the whitespaces correctly for the childs of group but messes up the formatting of the group tags itself.</p>
  
  <p>Second method was building an etree of the group with it's children </p>
  
  <pre><code>newgroup = ET.Element('group')
  ET.SubElement(newgroup, 'uuid').text = '%s' % g_uuid
  ET.SubElement(newgroup, 'id').text = '%s' % g_id
  ET.SubElement(newgroup, 'name').text = '%s' % g_name
  ET.SubElement(newgroup, 'desc').text = '%s' % g_desc
  
  access = root.find('access')
  access.append(newgroup)
  </code></pre>
  
  <p>But then the whole newgroup-tree appears in a single line without newlines and tabs at all:</p>
  
  <pre><code>&lt;group&gt;&lt;uuid&gt;f60e6b30-eec9-11e6-a5d4-2c768aabceca&lt;/uuid&gt;&lt;id&gt;2&lt;/id&gt;&lt;name&gt;newgroup&lt;/name&gt;&lt;desc&gt;Testing groups&lt;/desc&gt;&lt;/group&gt;&lt;/access&gt;
  </code></pre>
  
  <p>I am new to python and don't really know how to format strings. So how can I beautify this thing so that I get well formatted XML out of the script?</p>