sax is an event-driven api. Parsing XML documents using sax involves two parts:a parser and an event handler.The parser is responsible for reading the xml document and sending events to the event handler,Such as element start and end event;The event handler is responsible for responding to the event,Process the passed xml data.


import sys, string from xml.sax import handler, make_parser
class testhandler (handler.contenthandler):
 def __init __ (self):
 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 ()

In addition to dom, another way to read and write files.

  • Previous C # anonymous method and Delegate type conversion error analysis
  • Next Analysis of the usage of substr () and explode () functions in PHP