Python: lxml not pretty-printing newly added nodes
<p>I'm using a Python script to add nodes (or copy existing nodes) in an XML file. The script uses lxml library.  Here is existing snippet:</p>

<pre><code>&lt;entitlements&gt;
    &lt;bpuiEnabledForSubusers&gt;true&lt;/bpuiEnabledForSubusers&gt;
    &lt;appCodesAllowedForSubusers&gt;My Accounts,Bill Pay&lt;/appCodesAllowedForSubusers&gt;
    &lt;enabled&gt;true&lt;/enabled&gt;
    &lt;monitored&gt;true&lt;/monitored&gt;
&lt;/entitlements&gt;
</code></pre>

<p>So I use lxml to copy a node in the entitlements node. Then, when I </p>

<pre><code>return etree.tostring(self.root,encoding='unicode', pretty_print=True)
</code></pre>

<p>I get the following xml:</p>

<pre><code>&lt;entitlements&gt;
    &lt;bpuiEnabledForSubusers&gt;true&lt;/bpuiEnabledForSubusers&gt;
    &lt;appCodesAllowedForSubusers&gt;My Accounts,Bill Pay&lt;/appCodesAllowedForSubusers&gt;
    &lt;enabled&gt;true&lt;/enabled&gt;
    &lt;monitored&gt;true&lt;/monitored&gt;
&lt;appCodesAllowedForSubusersCopy&gt;My Accounts,Bill Pay&lt;/appCodesAllowedForSubusersCopy&gt;&lt;/entitlements&gt;
</code></pre>

<p>So the node is properly copied and added to the end of the child nodes, but in the XML it is not indented to the level of its siblings, and the parent's closing tag is on the same line, even though I used the pretty_print option.  Although the resulting XML is technically correct, it does not "look good" according to our existing standards.</p>

<p>Any idea why this is happening?</p>

<p>Thanks...</p>

<p><code>pretty_print=True</code> only has useful effect when your tree doesn't have trailing whitespace on the nodes already. Thus, you want to look at not just how your emit them, but how you're parsing them in the first place.</p>

<p>Use the <code>remove_blank_text=True</code> parser option:</p>

<pre><code>parser = etree.XMLParser(remove_blank_text=True)
</code></pre>

python xml lxml