import string
from Ft.Lib import pDomlette
from xml.dom import XML_NAMESPACE
from xml.xslt import XSL_NAMESPACE

def StripElements(node,stripElements,stripState=0):
    if node.nodeType == pDomlette.Node.DOCUMENT_NODE:
        for c in node.childNodes:
            StripElements(c,stripElements,stripState)
    elif node.nodeType == pDomlette.Node.ELEMENT_NODE:

        #See if we need to change the strip state
        if node.getAttributeNodeNS(XML_NAMESPACE,'space') == 'preserve':
            #Force the state to preserve
            stripState = 0
        elif node.getAttributeNodeNS(XML_NAMESPACE,'space'):
            #Force to strip
            stripState = 1
        else:
            #See if it is a perserve or strip element
            for (uri, local, strip) in stripElements:
                if (uri, local) in [(node.namespaceURI, node.localName), ('', '*'), (node.namespaceURI, '*')]:
                    stripState = strip
                    break

        for c in node.childNodes:
            StripElements(c,stripElements,stripState)
    elif node.nodeType == pDomlette.Node.TEXT_NODE:
        if stripState and not string.strip(node.data):
            #Kill'em all
            node.parentNode.removeChild(node)


