Last active
August 29, 2015 14:21
-
-
Save tomschr/6ecaaf69231dfbc9517a to your computer and use it in GitHub Desktop.
Gets the starting line number of the start-tag of root
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def root_sourceline(source, resolver=None): | |
"""Gets the starting line number of the start-tag of root | |
:param source: | |
:type source: file name/path, file object, file-like object, URL | |
:param etree.Resolver resolver: custom resolver | |
:return: (line number, column) | |
:rtype: tuple | |
""" | |
if hasattr(source, 'read'): | |
# We have a read() method, so it's a file-like object | |
buffer = io.StringIO(source.read()) | |
elif os.path.exists(source): | |
# path to a file | |
buffer = io.StringIO(open(source, 'r').read()) | |
else: | |
# We expect a string here | |
buffer = io.StringIO(source) | |
import xml.sax.handler | |
class MyContentHandler(xml.sax.handler.ContentHandler): | |
def __init__(self): | |
ContentHandler.__init__(self) | |
# initialize your handler | |
self.root = None | |
def startElement(self, name, attrs): | |
if isinstance(self.root, tuple): | |
return | |
loc = self._locator | |
if loc is not None: | |
line, col = loc.getLineNumber(), loc.getColumnNumber() | |
else: | |
line, col = None, None | |
self.root = (line, col) | |
parser = xml.sax.make_parser() | |
handler = MyContentHandler() | |
parser.setContentHandler(handler) | |
parser.parse(source) | |
return handler.root |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment