[XML-SIG] insert_whitespace function

Jeffrey Chang jefftc@leland.Stanford.EDU
Thu, 22 Jul 1999 12:29:10 -0700 (PDT)

Hello everybody,

I've written an insert_whitespace function that complements the
functionality of xml.dom.utils.strip_whitespace.  Given a DOM tree with no
extraneous whitespace, it will insert some so that the tree can be printed
prettily with toxml().

I hope that this would eventually be added to the utils.py file as I
believe it is useful.

I do not have any really elaborate XML documents to test this on, so if
you find some cases where this function fails, please send them to me.


from xml.dom import core 
def insert_whitespace(node, spacing=2, indent=0): 
    """insert_whitespace(node[, spacing=2]) 

    Format a DOM tree prettily by inserting whitespace where appropriate. 
    spacing specifies the number of spaces to indent. 

    This assumes that the tree has been stripped of whitespace. 
    indented_types = [core.ELEMENT_NODE, # which node types to indent

    doc = node.get_ownerDocument() 
    if(doc is None):  # I'm the root node, start the recursion
        for child in node.childNodes[:]: 
            insert_whitespace(child, spacing=spacing, indent=indent) 

    indent_str = "\n" + " "*(indent+spacing) 

    indented=0       # has anything been indented? 
    for child in node.childNodes[:]: 
        if(child.nodeType in indented_types): 
            node.insertBefore(doc.createTextNode(indent_str), child) 
        insert_whitespace(child, spacing=spacing, indent=indent+spacing) 
    if(indented):    # need to indent my close tag
        node.appendChild(doc.createTextNode("\n" + " "*indent))