Skip to content

Instantly share code, notes, and snippets.

@nskeip
Created September 20, 2012 09:15
Show Gist options
  • Save nskeip/3754851 to your computer and use it in GitHub Desktop.
Save nskeip/3754851 to your computer and use it in GitHub Desktop.
making an xml-parser more readable: an abstract target that tries to call methods like TAGNAME_start, TAGNAME_end etc.
class AbstractParseTarget(object): # http://lxml.de/parsing.html#the-target-parser-interface
def __init__(self):
self.current_tag = None
def start(self, tag, attrib):
self.current_tag = tag
method = getattr(self, '%s_start' % tag, None)
if method:
method(attrib)
def end(self, tag):
method = getattr(self, '%s_end' % tag, None)
if method:
method()
self.current_tag = None
def close(self):
self.current_tag = None
def data(self, data):
if self.current_tag is None:
return
method = getattr(self, '%s_data' % self.current_tag, None)
if method:
method(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment