Expat current line/column number

Alan Kennedy alanmk at hotmail.com
Wed Oct 15 14:54:08 EDT 2003


[Nicolas Fleury]
>>> Is it possible with xml.parsers.expat to get the current line and
>>> column number if an exception is raised by one of the callbacks (not
>>> necessary an xml.parsers.expat.ExpatError)?

[Alan Kennedy]
>> Is this the type of thing you mean?

[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 :-p 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.

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan




More information about the Python-list mailing list