minidom appendchild/insertBefore

minidom, python, xml

Solution

Have you tried just inserting a newline in a text node?

# Put this after your existing code
newline = doc.createTextNode('\n')
calcSequence.insertBefore(newline, entrys[2])

Problem

I'm using Python and minidom to insert Data in an existing XML-file. When I do so, I get correct XML-code but it doesn't look as I want it. This is an example for my xml-file at the beginning. ``` <?xml version="1.0" ?> <sim> <tool name="A"/> <calcSequence> <entry>FD_so</entry> <entry>FD_ped</entry> <entry>FD_veh</entry> </calcSequence> </sim> ``` Now the code: ``` calcSequence = doc.getElementsByTagName('calcSequence')[0] entrys = calcSequence.getElementsByTagName('entry') hnode = doc.createElement('entry') htext = doc.createTextNode('test') hnode.appendChild(htext) calcSequence.insertBefore(hnode,entrys[2]) ``` And the result: ``` <calcSequence> <entry>FD_so</entry> <entry>FD_ped</entry> <entry>test</entry><entry>FD_veh</entry> </calcSequence> ``` Is there a way to insert the missing newline between the 2 `<entry>`s? doc.toprettyxml() isn't a solution, since this is only a small part of the xml, and I do not want to insert blank lines after every line in the document.

Original source