Expat current line/column number

Nicolas Fleury nid_oizo at yahoo.com_remove_the_
Wed Oct 15 15:03:24 EDT 2003


Nicolas Fleury wrote:

> Alan Kennedy wrote:
> 
>> [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)?
>>
>>
>>
>> Is this the type of thing you mean?
> 
> 
> It doesn't work on my side or I'm missing something.

ok the solution is get the line and column number during parsing. 
Here's a working example:

import StringIO
import xml.sax
import xml.sax.xmlreader
import xml.sax.expatreader

class ApplicationException(Exception): pass

class HandlerThatRaisesExceptions(xml.sax.ContentHandler):
     def startElement(self, name, attrs):
         if name == 'hello':
             raise Exception('wrong at line ' + 
str(parser.getLineNumber()) +
                             ' and column ' + str(parser.getColumnNumber()))

inputfile = StringIO.StringIO("""
<well>
     <formed/>
     <xyz>
         <hello/>
     </xyz>
</well>
""")

parser = xml.sax.make_parser(['xml.sax.expatreader'])
parser.setContentHandler(HandlerThatRaisesExceptions())
parser.parse(inputfile)






More information about the Python-list mailing list