[XML-SIG] DOM walker examples
Kevin Russell
krussll@cc.UManitoba.CA
Tue, 23 Feb 1999 20:23:11 -0600
I notice the XML howto still has a blank space for examples
of DOM walking. I've finally wrapped my head around
CVS (by the way, is it a good idea for the howto to talk about
stuff that's only available through CVS and not from the ordinary
web-site?) and played around with it. A couple of my toy
programs might be appropriate howto-examples, so here
they are.
-- Kevin Russell
--------------
"""killnote.py
A DOM-walker example: remove all "note" elements from a document
"""
from xml.dom import utils, walker
from sys import argv
class NoteKiller (walker.Walker):
def startElement(self,node):
if node.nodeName == 'note':
node.parentNode.removeChild(node)
if __name__ == '__main__':
f = utils.FileReader()
doc = f.readFile(argv[1])
NoteKiller().walk(doc)
print doc.toxml()
---------------
"""renumber.py
A DOM-walker example: give each element a unique ID attribute
"""
from xml.dom import utils, walker
from sys import argv
class NumberingWalker (walker.Walker):
counters = {}
def startElement(self,node):
try:
self.counters[node.nodeName] = self.counters[node.nodeName]
+ 1
except KeyError:
self.counters[node.nodeName] = 1
node.setAttribute('id', '%s%s' % (node.nodeName,
self.counters[node.nodeName]))
if __name__ == '__main__':
f = utils.FileReader()
doc = f.readFile(argv[1])
NumberingWalker().walk(doc)
print doc.toxml()