Simple Use of Locator Object Methods : SAX « XML « Python






Simple Use of Locator Object Methods

 
import sys
from xml.sax import saxutils
from xml.sax import make_parser
from xml.sax import handler

class SimpleHandler(saxutils.DefaultHandler):
    # Obtain a locator object
    def setDocumentLocator(self,locator):
        self.locator = locator

    def startElement(self,name,attrs):
        col = self.locator.getColumnNumber()
        line = self.locator.getLineNumber()
        pubid = self.locator.getPublicId()
        sysid = self.locator.getSystemId()
        print 'startElement (%d,%d,%s,%s): %s' % (line,col,pubid,sysid,name)

    def endElement(self,name):
        col = self.locator.getColumnNumber()
        line = self.locator.getLineNumber()
        pubid = self.locator.getPublicId()
        sysid = self.locator.getSystemId()
        print 'endElement (%d,%d,%s,%s): %s' % (line,col,pubid,sysid,name)

    def characters(self,data):
        print 'characters: ', repr(data)

parser = make_parser()
sh = SimpleHandler()
parser.setContentHandler(sh)
parser.parse(sys.argv[1])

   
  








Related examples in the same category

1.Identifying End Element Tags Using SAX Parsing
2.SAX-Based Analysis of the Guacamole Recipe
3.Structure of a Program to Process a Document with a _DTD Using SAX