July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Mark Nenadov
The expat
parser is normally used through the SAX interface, but sometimes you
may want to use expat directly to extract the best
possible performance.
Python is very explicit about the lower-level mechanisms that its higher-level modules’ packages use. You’re normally better off accessing the higher levels, but sometimes, in the last few stages of an optimization quest, or just to gain better understanding of what, exactly, is going on, you may want to access the lower levels directly from your code. For example, here is how you can use Expat directly, rather than through SAX:
import xml.parsers.expat, sys
class MyXML:
Parser = ""
# Prepare for parsing
def _ _init_ _(self, xml_filename):
assert xml_filename != ""
self.xml_filename = xml_filename
self.Parser = xml.parsers.expat.ParserCreate( )
self.Parser.CharacterDataHandler = self.handleCharData
self.Parser.StartElementHandler = self.handleStartElement
self.Parser.EndElementHandler = self.handleEndElement
# Parse the XML file
def parse(self):
try:
xml_file = open(self.xml_filename, "r")
except:
print "ERROR: Can't open XML file %s"%self.xml_filename
raise
else:
try: self.Parser.ParseFile(xml_file)
finally: xml_file.close( )
# to be overridden by implementation-specific methods
def handleCharData(self, data): pass
def handleStartElement(self, name, attrs): pass
def handleEndElement(self, name): passThis recipe presents a reusable way to use ...
Read now
Unlock full access