pretty print xml document

Adrian Eyre a.eyre at optichrome.com
Tue Feb 8 13:07:05 EST 2000


> I want to pretty print an xml document that I've created :

You might get a better response on XML issues if you post to
the XML-SIG list. Anyway - from one of the XML-SIG lot (can't
remember which):

def formatDOM(node, spacing = 2, indent = 0):
    """formatDOM(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
                      core.PROCESSING_INSTRUCTION,
                      core.COMMENT_NODE]

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

    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) 
            indented=1
        formatDOM(child, spacing=spacing, indent=indent+spacing) 
            
    if(indented):    # need to indent my close tag
        node.appendChild(doc.createTextNode("\n" + " "*indent))

-----------------------------------------------------------------
Adrian Eyre <a.eyre at optichrome.com> - http://www.optichrome.com 





More information about the Python-list mailing list