Sax is an event-based-driven API. Using SAX to parse XML documents involves two parts: parsers and event handlers. The parser is responsible for reading the XML document and sending events to the event handler, such as when the element starts with the element end event, and the event handler is responsible for handling the passed XML data by responding to the event.
Instance:
Copy Code code as follows:
Import sys, string from xml.sax import handler, Make_parser
Class Testhandler (handler. ContentHandler):
def __init__ (self):
Pass
def startdocument (self):
Print "Document Start ..."
def enddocument (self):
Print "Document end ..."
def startelement (self, Name, attrs):
print ' start tag: ', name
def endelement (self, name):
print ' end tag: ', name
def characters (self, chrs):
Print chrs
def test ():
Handler = Testhandler ()
Parser = Make_parser ()
Parser.setcontenthandler (Handler)
f = open (Sys.argv[1], ' R ')
Parser.parse (f)
F.close ()
if __name__ = = ' __main__ ':
Test ()
Another way to read and write files in addition to the DOM.