title: How to pretty print an xml file in Python?
body: <p>I'd like to tidy a complicated xml file, using lxml. The problem is it has many elements which have tail. For example, there's an xml like this:</p>
  
  <pre><code> &lt;body&gt;&lt;part&gt;n&lt;/part&gt; attend &lt;/body&gt;
  </code></pre>
  
  <p>I want to tidy this into this:</p>
  
  <pre><code> &lt;body&gt;
      &lt;part&gt;n&lt;/part&gt; attend 
   &lt;/body&gt;
  </code></pre>
  
  <p>I tried to apply pretty_print with remove_blank_text parser in lxml at first. But it failed.</p>
  
  <pre><code>import lxml.etree as ET
  xml_doc = '&lt;body&gt;&lt;part&gt;n&lt;/part&gt; attend &lt;/body&gt;'
  parser = ET.XMLParser(remove_blank_text=True)
  root = ET.fromstring(xml_doc, parser)
  print(ET.tostring(root, pretty_print=True))
  &gt;&gt;&gt;b'&lt;body&gt;&lt;part&gt;n&lt;/part&gt; attend &lt;/body&gt;\n'
  </code></pre>
  
  <p>And then, I tried again without applying the parser to no avail.</p>
  
  <pre><code>import lxml.etree as ET
  xml_doc = '&lt;body&gt;&lt;part&gt;n&lt;/part&gt; attend &lt;/body&gt;'
  root = ET.fromstring(xml_doc)
  print(ET.tostring(root, pretty_print=True))
  &gt;&gt;&gt;b'&lt;body&gt;&lt;part&gt;n&lt;/part&gt; attend &lt;/body&gt;\n'
  </code></pre>