<s> """<STR_LIT>""" <EOL> import xml . sax <EOL> from xml . sax . handler import ContentHandler <EOL> def parse ( file ) : <EOL> doc = Node ( "<STR_LIT:root>" ) <EOL> xml . sax . parse ( file , Builder ( doc ) ) <EOL> return doc <EOL> def parseString ( string ) : <EOL> doc = Node ( "<STR_LIT:root>" ) <EOL> xml . sax . parseString ( string , Builder ( doc ) ) <EOL> return doc <EOL> class Node ( object ) : <EOL> def __init__ ( self , name , attrs = None , text = None , parent = None ) : <EOL> self . name = name <EOL> self . attrs = attrs <EOL> self . text = text <EOL> self . parent = parent <EOL> self . children = [ ] <EOL> if parent != None : <EOL> parent . children . append ( self ) <EOL> def get_bool ( self , key , default = False ) : <EOL> v = self . get ( key ) <EOL> if v == None : <EOL> return default <EOL> else : <EOL> return bool ( int ( v ) ) <EOL> def index ( self ) : <EOL> if self . parent : <EOL> return self . parent . children . index ( self ) <EOL> else : <EOL> return <NUM_LIT:0> <EOL> def has ( self , key ) : <EOL> try : <EOL> self [ key ] <EOL> return True <EOL> except KeyError : <EOL> return False <EOL> except IndexError : <EOL> return False <EOL> def get ( self , key , default = None ) : <EOL> if self . has ( key ) : <EOL> return self [ key ] <EOL> else : <EOL> return default <EOL> def __getitem__ ( self , key ) : <EOL> if callable ( key ) : <EOL> return filter ( key , self . children ) <EOL> else : <EOL> t = key . __class__ <EOL> meth = "<STR_LIT>" % t . __name__ <EOL> if hasattr ( self , meth ) : <EOL> return getattr ( self , meth ) ( key ) <EOL> else : <EOL> raise KeyError ( key ) <EOL> def __getstr__ ( self , name ) : <EOL> if name [ : <NUM_LIT:1> ] == "<STR_LIT:@>" : <EOL> return self . attrs [ name [ <NUM_LIT:1> : ] ] <EOL> else : <EOL> return self [ lambda nd : nd . name == name ] <EOL> def __getint__ ( self , index ) : <EOL> return self . children [ index ] <EOL> def __iter__ ( self ) : <EOL> return iter ( self . children ) <EOL> def path ( self ) : <EOL> if self . parent == None : <EOL> return "<STR_LIT>" % self . name <EOL> else : <EOL> return "<STR_LIT>" % ( self . parent . path ( ) , self . name ) <EOL> class Builder ( ContentHandler ) : <EOL> def __init__ ( self , start = None ) : <EOL> self . node = start <EOL> def __setitem__ ( self , element , type ) : <EOL> self . types [ element ] = type <EOL> def startElement ( self , name , attrs ) : <EOL> self . node = Node ( name , attrs , None , self . node ) <EOL> def endElement ( self , name ) : <EOL> self . node = self . node . parent <EOL> def characters ( self , content ) : <EOL> if self . node . text == None : <EOL> self . node . text = content <EOL> else : <EOL> self . node . text += content </s>
