[Nicolas Fleury]
[Alan Kennedy]
[Code elided]
[Nicolas Fleury]
This is exactly what I mean. Unfortunately, I've use the parser in
xml.parsers.expat and not xml.sax, and it seems that parser only
provides line and column numbers for its own exceptions.
Ah. I think this solves the problem.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import StringIO
import xml.parsers.expat
class AppExc(Exception):
def __init__(self, elem, line, col):
self.elem, self.line, self.col = elem, line, col
def __str__(self):
return "Yucky %s
Line %d, Col %d" % \
(self.elem, self.line, self.col)
def endElementHandler(elemname):
global parser
if elemname == 'bluveny':
raise AppExc(elemname, parser.ErrorLineNumber, \
parser.ErrorColumnNumber)
inputfile = StringIO.StringIO("""
<cheeses>
<limburger/>
<stilton/>
<gruyere/>
<jarlsburg/>
<dorset><bluveny/></dorset>
</cheeses>
""")
parser = xml.parsers.expat.ParserCreate()
parser.EndElementHandler = endElementHandler
try:
parser.ParseFile(inputfile)
except AppExc, ax:
print str(ax)
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Not quite as clean though, because of the requirement to declare
'parser' as a global. To get rid of the 'global' declaration, you
could always wrap up your handlers in a class, and set the parser as
an attribute of each instance.