]> git.llucax.com Git - software/bife/byfe.git/blob - byfe/parser.py
Added an experimental implementation of BIFE in python.
[software/bife/byfe.git] / byfe / parser.py
1 # vim: set expandtab tabstop=4 shiftwidth=4:
2
3 from xml.sax import saxutils, make_parser
4 from os      import sep
5
6 class Parser(xml.sax.saxutils.DefaultHandler):
7     """ByFE XML Parser."""
8
9     def __init__(self, fallback = None, cache = os.sep + 'tmp'):
10         """Constructor."""
11         self.fallback = fallback
12         self.cache    = cache
13         self.parser   = xml.sax.make_parser()
14         self.parser.setFeature(xml.sax.handler.feature_namespaces, 0)
15         self.parser.setContentHandler(self)
16
17     def startElement(self, name, attrs): # FIXME - arreglar a partir de aca.
18         """Start element handler."""
19         mods = name.lower().split('.')
20         classname = path.pop()
21         modulename = 'bife.' + mods.join('.')
22         try:
23             module   = __import__(modulename, None, None, True)
24             classobj = getattr(module, classname)
25             obj      = classobj(attrs)
26         except:
27             #if self.fallback:
28                 obj = self.fallback(name, attrs)
29             #else:
30             #    raise "Class not found '$class'."
31         self.stack[] = obj
32
33     def endElement(self, name):
34         """End element handler."""
35         end(self.stack)
36         current = self.stack[key(self.stack)]
37         self.stack.pop()
38         end(self.stack)
39         parent = self.stack[key(self.stack)]
40         if parent:
41             parent.addContents(current)
42         else:
43             self.root = current
44
45     def characters(self, data):
46         """Caracter data handler."""
47         end(self.stack)
48         current = self.stack[key(self.stack)]
49         current.addContents(data)
50
51     def parse(self, file):
52         # TODO - cache
53         if !self.parser.parse(self.parser, file)
54
55     def parseString(self, string):
56         if !self.parser.parseString(self.parser, string, self)