xml.dom.minidom appendChild/toxml formatting problem

Ray rrarey at gmail.com
Fri Nov 5 16:30:28 EST 2004


I have put together some pretty simple code for adding and removing
elements from an XML file, but am having a problem with toxml writing
out the correct format after I have called appendChild on a node.

Here is a snippet:

if (action == 'add'):
   newCluster = domi.createElement(elementType)
   newCluster.setAttribute("Name", elementName)
   elem.appendChild(newCluster)
else:
   elem.removeChild(childElem)

domi.normalize()

configFile = open(self.flist[0], "w")
newDoc = domi.toxml()
configFile.write(newDoc)
configFile.close()

Basically, if I start out with a Cluster that looks like this in the
XML file:
<Cluster Name="RAYTEST">
   <Cluster Name="RAYTEST2"/>
</Cluster>

and then use the createElement, setAttribute, and appendChild lines
from above to add a new Cluster called "RAYTEST3" to the "RAYTEST2"
Cluster, after calling domi.normalize(), domi.toxml(), and
configFile.write(), the XML looks like:
<Cluster Name="RAYTEST">
   <Cluster Name="RAYTEST2"><Cluster Name="RAYTEST3"/></Cluster>
</Cluster>

instead of how I would like it to look, which would be:
<Cluster Name="RAYTEST">
   <Cluster Name="RAYTEST2">
      <Cluster Name="RAYTEST3"/>
   </Cluster>
</Cluster>

Or, if I append "RAYTEST3" to "RAYTEST", it comes out as:
<Cluster Name="RAYTEST">
   <Cluster Name="RAYTEST2"/>
<Cluster Name="RAYTEST3"/></Cluster>

Instead of:
<Cluster Name="RAYTEST">
   <Cluster Name="RAYTEST2"/>
   <Cluster Name="RAYTEST3"/>
</Cluster>


The rest of the XML file retains its original whitespace and
linebreaks.  How can I get this to format the new changes correctly? 
Calling toprettyxml instead of toxml seems to double the whitespace
and linebreaks in the rest of the file.



More information about the Python-list mailing list