[XML-SIG] Namespace Stripper Filter
Clark C. Evans
cce@clarkevans.com
Mon, 19 Mar 2001 07:21:07 -0500 (EST)
Here is my first "real live" python program... anyone who'd
like to comment for style, please do so as I'm a newbie.
-----------------------------------------------------------------
"""Strips a particular namespace from an XML document."""
from xml.sax import saxutils
class StripperFilter(saxutils.XMLFilterBase ):
"""Does the actual stripping"""
def __init__(self,nmsp):
"""The namespace to strip is nmsp"""
saxutils.XMLFilterBase.__init__(self)
self.nmsp = nmsp
self.depth = 0
def startElementNS(self, name, qname, attrs):
"""Ignores elements and strips attributes of nmsp"""
if name[0] != self.nmsp:
#
# Warning: For efficiency this dives into the
# underlying representation of AttributesNSImpl
# and deletes attributes to be stripped.
#
# _attrs should be of the form {(ns_uri, lname): value, ...}.
# _qnames of the form {(ns_uri, lname): qname, ...}."""
#
for (ns_uri,lname) in attrs._attrs.keys():
if self.nmsp == ns_uri: del attrs._attrs[(ns_uri,lname)]
self._cont_handler.startElementNS(name,qname,attrs)
else:
self.depth = self.depth + 1
def characters(self, content):
if self.depth == 0:
saxutils.XMLFilterBase.characters(self,content)
def endElementNS(self, name, qname):
if self.depth > 0:
self.depth = self.depth - 1
else:
self._cont_handler.endElementNS(name,qname)
def startPrefixMapping(self, prefix, uri):
if self.nmsp != uri:
self._cont_handler.startPrefixMapping(prefix, uri)
from xml.sax import make_parser
from xml.sax.handler import feature_namespaces
def testStripper():
parser = make_parser()
parser.setFeature(feature_namespaces, 1)
strip = StripperFilter('namespace-to-strip)
out = saxutils.XMLGenerator()
strip.setContentHandler(out)
parser.setContentHandler(strip)
parser.parse("test.xml")
if __name__ == '__main__':
testStripper()