[XML-SIG] minidom.Element.writexml() change

Joel Lawhead jlawhead@bellsouth.net
Thu, 14 Nov 2002 23:56:26 -0600


Hi,

I altered the writexml() method of the Element class in minidom so the
tags 
for text elements are on the same line as the data they contain.

The standard minidom.Element.writexml() produces output like this:

<?xml version="1.0" ?>
<TileMeta>
	<Id>
		<Theme>
			Photo
		</Theme>
		<Scale>
			Scale64m
		</Scale>
		<X>
			60
		</X>
		<Y>
			277
		</Y>
	</Id>
	<TileExists>
		true
	</TileExists>
</TileMeta>

My modified minidom.Element.writexml() produces more readable output
like this:

<?xml version="1.0" ?>
<TileMeta>
	<Id>
		<Theme>Photo</Theme>
		<Scale>Scale64m</Scale>
		<Scene>15</Scene>
		<X>60</X>
		<Y>277</Y>
	</Id>
	<TileExists>true</TileExists>
</TileMeta>

The forums on the xml-sig SoureForge page seem to be broken so I'm
posting the method here:

def writexml(self, writer, indent="", addindent="", newl=""): 
    """This version of write xml makes sure text nodes are 
    surrounded by tags for easier reading rather than being 
    on lines by themselves."""  
    
        # indent = current indentation
        # addindent = indentation to add to higher levels
        # newl = newline string
        writer.write(indent+"<" + self.tagName)

        attrs = self._get_attributes()
        a_names = attrs.keys()
        a_names.sort()

        for a_name in a_names:
            writer.write(" %s=\"" % a_name)
            _write_data(writer, attrs[a_name].value)
            writer.write("\"")
        if self.childNodes:
            writer.write(">%s"%(newl))
            for node in self.childNodes:
                 if node.nodeType!=node.TEXT_NODE: 
                   
node.writexml(writer,indent+addindent,addindent,newl)
                 else:
                    writer.seek(writer.tell()-1)
                    node.writexml(writer,"",addindent,"")
            if self.childNodes[-1].nodeType!=node.TEXT_NODE:
                writer.write("%s</%s>%s" % (indent,self.tagName,newl))
            else:   writer.write("</%s>%s" % (self.tagName,newl))
        else:
            writer.write("/>%s"%(newl))

The minidom.Element.toprettyxml() method calls writexml() normally but
the problem is the output isn't that pretty (IMHO). The above method
produces a more compact, readable "pretty xml" output.

Thanks,
Joel Lawhead
jlawhead@nvisionsolutions.com