prettify adding extra lines in xml
<p>I'm using Prettify to make my XML file readable. I am adding some new info in to an excising XML file but when i save it to a file i get extra lines in between the lines. is there a way of removing these line? Below is the code i'm using </p>

<pre><code>import xml.etree.ElementTree as xml
import xml.dom.minidom as  minidom
from lxml import etree

def prettify(elem):
    rough_string = xml.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")


cid = "[123,123,123,123,123]"

doc = xml.parse('test.xml')
root = doc.getroot()

root.getchildren().index(root.find('card'))

e = xml.Element('card')
e.set('id', cid)
n = xml.SubElement(e, "name")
n.text = "FOLDER"
r = xml.SubElement(e, "red")
r.text = "FILE.AVI"
g = xml.SubElement(e, "green")
g.text = "FILE.AVI"
b = xml.SubElement(e, "blue")
b.text = "FILE.AVI"

root.insert(0, e)

doc2 =  prettify(root)

with open("testnew.xml", "w") as f:
    f.write(doc2)
</code></pre>

<p>Below is what i get in the file</p>

<pre><code>&lt;data&gt;


    &lt;card id="[123,123,123,123,123]"&gt;
            &lt;name&gt;FOLDER&lt;/name&gt;
            &lt;red&gt;FILE.AVI&lt;/red&gt;
            &lt;green&gt;FILE.AVI&lt;/green&gt;
            &lt;blue&gt;FILE.AVI&lt;/blue&gt;
    &lt;/card&gt;
    &lt;card id="[000,000,000,000,000]"&gt;


            &lt;name&gt;Colours&lt;/name&gt;


            &lt;red&gt;/media/usb/cow.avi&lt;/red&gt;


            &lt;green&gt;/media/usb/pig.avi&lt;/green&gt;


            &lt;blue&gt;/media/usb/cat.avi&lt;/blue&gt;


    &lt;/card&gt;


&lt;/data&gt;
</code></pre>

<p>input file "test.xml" looks like </p>

<pre><code>&lt;data&gt;
   &lt;card id="[000,000,000,000,000]"&gt;
        &lt;name&gt;Colours&lt;/name&gt;
        &lt;red&gt;/media/usb/cow.avi&lt;/red&gt;
        &lt;green&gt;/media/usb/pig.avi&lt;/green&gt;
        &lt;blue&gt;/media/usb/cat.avi&lt;/blue&gt;
   &lt;/card&gt;
&lt;/data&gt;
</code></pre>

<p>The new content added is being printed fine. Removing any "prettification" of the existing text solves the issue </p>

<p>Add </p>

<pre><code>for elem in root.iter('*'):
    if elem == e:
        print "Added XML node does not need to be stripped"
        continue
    if elem.text is not None:
        elem.text = elem.text.strip()
    if elem.tail is not None:
        elem.tail = elem.tail.strip()
</code></pre>

<p>before calling</p>

<pre><code> doc2 =  prettify(root)
</code></pre>

<p>Related answer: <a href="http://stackoverflow.com/questions/19288469/python-how-to-strip-white-spaces-from-xml-text-nodes">Python how to strip white-spaces from xml text nodes</a></p>

python xml prettify