xml.dom.minidom appendChild/toxml formatting problem

Jeremy Jones zanesdad at bellsouth.net
Fri Nov 5 17:11:04 EST 2004


Ray wrote:

>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()
>
>
>  
>
<snip>

>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.
>  
>
I'd like to offer you a more automated method, but I can't.  Perhaps 
someone else can.  The only way I can think of to do it is to see what 
kind of text nodes exist around where you are inserting your elements 
and get that for formatting and insert similar text nodes before you 
insert your elements.

Just out of curiosity, why are you interested in preserving the 
whitespace?  Is this going to be something that is human read rather 
than machine read (or human read in addition to machine read)?


Jeremy Jones




More information about the Python-list mailing list