Debian Codegraph @

tools/python/mllib/parsers.py

raw
1 #
2 # Licensed to the Apache Software Foundation (ASF) under one
3 # or more contributor license agreements. See the NOTICE file
4 # distributed with this work for additional information
5 # regarding copyright ownership. The ASF licenses this file
6 # to you under the Apache License, Version 2.0 (the
7 # "License"); you may not use this file except in compliance
8 # with the License. You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing,
13 # software distributed under the License is distributed on an
14 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 # KIND, either express or implied. See the License for the
16 # specific language governing permissions and limitations
17 # under the License.
18 #
19
20 """
21 Parsers for XML to dom.
22 """
23 from __future__ import absolute_import
24
25 import xml.sax.handler
26 from .dom import *
27
28
29 class Parser:
30
31 def __init__(self):
32 self.tree = Tree()
33 self.node = self.tree
34 self.nodes = []
35
36 def line(self, id, lineno, colno):
37 while self.nodes:
38 n = self.nodes.pop()
39 n._line(id, lineno, colno)
40
41 def add(self, node):
42 self.node.add(node)
43 self.nodes.append(node)
44
45 def start(self, name, attrs):
46 tag = Tag(name, *attrs)
47 self.add(tag)
48 self.node = tag
49
50 def end(self, name):
51 self.balance(name)
52 self.node = self.node.parent
53
54 def data(self, data):
55 children = self.node.children
56 if children and isinstance(children[-1], Data):
57 children[-1].data += data
58 else:
59 self.add(Data(data))
60
61 def comment(self, comment):
62 self.add(Comment(comment))
63
64 def entity(self, ref):
65 self.add(Entity(ref))
66
67 def character(self, ref):
68 self.add(Character(ref))
69
70 def balance(self, name=None):
71 while self.node != self.tree and name != self.node.name:
72 self.node.parent.extend(self.node.children)
73 del self.node.children[:]
74 self.node.singleton = True
75 self.node = self.node.parent
76
77
78 class XMLParser(xml.sax.handler.ContentHandler):
79
80 def __init__(self):
81 self.parser = Parser()
82 self.locator = None
83
84 def line(self):
85 if self.locator is not None:
86 self.parser.line(self.locator.getSystemId(),
87 self.locator.getLineNumber(),
88 self.locator.getColumnNumber())
89
90 def setDocumentLocator(self, locator):
91 self.locator = locator
92
93 def startElement(self, name, attrs):
94 self.parser.start(name, attrs.items())
95 self.line()
96
97 def endElement(self, name):
98 self.parser.end(name)
99 self.line()
100
101 def characters(self, content):
102 self.parser.data(content)
103 self.line()
104
105 def skippedEntity(self, name):
106 self.parser.entity(name)
107 self.line()