2.2a Sample SAX Program

import sys
from xml.sax import saxlib, saxexts, drivers

class PrintWorkNumbers(saxlib.HandlerBase):
    """This is our specialized document handler class"""
    def __init__(self):
        self.curr_name = ''
        self.print_flag = 0

    def startElement(self, name, attribs):
        if name == 'NAME':
            sys.stdout.write('Name: ')
            self.print_flag = 1
        elif name == 'PHONENUM':
            if attribs['DESC'] == 'Work':
            &nb sp;   sys.stdout.write('Work phone number: ')
            &nb sp;   self.print_flag = 1

    def endElement(self, name):
        if self.print_flag:
            self.print_flag = 0
            print    #write new line
        if name == 'NAME':
            self.curr_name = name

    def characters(self, ch, start, length):
        if self.print_flag:
            sys.stdout.write(ch[start:start+length])
 

p = saxexts.XMLValParserFactory.make_parser()
p.setDocumentHandler(PrintWorkNumbers())
xml_file = open(sys.argv[1], 'r')
p.parseFile(xml_file)
xml_file.close()