PyLucene 3.4.0-1 import
[pylucene.git] / samples / LuceneInAction / lia / handlingtypes / xml / Digester.py
1 # ====================================================================
2 #   Licensed under the Apache License, Version 2.0 (the "License");
3 #   you may not use this file except in compliance with the License.
4 #   You may obtain a copy of the License at
5 #
6 #       http://www.apache.org/licenses/LICENSE-2.0
7 #
8 #   Unless required by applicable law or agreed to in writing, software
9 #   distributed under the License is distributed on an "AS IS" BASIS,
10 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 #   See the License for the specific language governing permissions and
12 #   limitations under the License.
13 # ====================================================================
14
15 import xml.sax
16
17
18 class Digester(xml.sax.ContentHandler):
19
20     attributes = {}
21     tags = {}
22
23     def addSetProperty(self, path, property, attribute=None):
24
25         if attribute is not None:
26             pairs = self.attributes.get(path)
27             if pairs is None:
28                 self.attributes[path] = pairs = { attribute: property }
29             else:
30                 pairs[property] = attribute
31
32         else:
33             self.tags[path] = property
34
35     def parse(self, input):
36
37         xml.sax.parse(input, self)
38         return self.properties
39     
40     def startDocument(self):
41
42         self.properties = {}
43         self.path = []
44
45     def startElement(self, tag, attrs):
46
47         self.path.append(tag)
48         pairs = self.attributes.get('/'.join(self.path))
49         if pairs is not None:
50             for name, value in attrs.items():
51                 property = pairs.get(name)
52                 if property is not None:
53                     self.properties[property] = value
54
55     def characters(self, data):
56
57         self.data = data.strip()
58
59     def endElement(self, tag):
60
61         if self.data:
62             property = self.tags.get('/'.join(self.path))
63             if property is not None:
64                 self.properties[property] = self.data
65             self.data = None
66             
67         self.path.pop()