Electricmonk

Ferry Boender

Programmer, DevOpper, Open Source enthusiast.

Blog

XPath and line numbers in Python

Thursday, August 25th, 2005

Something so simple, yet so hard to figure out. I’ve been strugling on and off with something for over a couple weeks. Here’s the deal:

I’m using the Python SAX module in combination with XPath to find my way through an XML-based configuration file. When an incorrect option or value is given, I raise an exception about the problem. However, I’d also like to let the user know the exact line number at which the problem occured.

I’ve already given up on displaying the exact line number. Due to the fact that a single XML element can span multiple lines and the way XML is parsed, it’s probably too impossible to get the real line number. Instead, I’ve settled for the line at which the element began. So when the element tag is openened on line 5 and the attributes span multiple lines, I’ll settle for reporting the problem as being on line 5.

But I can’t even get that to work in Python. I’ve went through the API, googled my ass off, but all I can find is some vague reference about locators.

For something they make out to be so simple and easy to use, XML (or rather the parsers and gazillion of different parsing libraries/methods) sure is a bitch to use.

The text of all posts on this blog, unless specificly mentioned otherwise, are licensed under this license.