Debian Codegraph @

tools/python/mllib/__init__.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 This module provides document parsing and transformation utilities for XML.
22 """
23
24 from __future__ import absolute_import
25
26 import os
27 import sys
28 import xml.sax
29 import types
30 from xml.sax.handler import ErrorHandler
31 from xml.sax.xmlreader import InputSource
32
33 try:
34 from io import StringIO
35 except ImportError:
36 from cStringIO import StringIO
37
38 if sys.version_info[0] == 2:
39 import types
40 CLASS_TYPES = (type, types.ClassType)
41 else:
42 CLASS_TYPES = (type,)
43
44 from . import dom
45 from . import transforms
46 from . import parsers
47
48
49 def transform(node, *args):
50 result = node
51 for t in args:
52 if isinstance(t, CLASS_TYPES):
53 t = t()
54 result = result.dispatch(t)
55 return result
56
57
58 class Resolver:
59
60 def __init__(self, path):
61 self.path = path
62
63 def resolveEntity(self, publicId, systemId):
64 for p in self.path:
65 fname = os.path.join(p, systemId)
66 if os.path.exists(fname):
67 source = InputSource(systemId)
68 source.setByteStream(open(fname))
69 return source
70 return InputSource(systemId)
71
72
73 def xml_parse(filename, path=()):
74 h = parsers.XMLParser()
75 p = xml.sax.make_parser()
76 p.setContentHandler(h)
77 p.setErrorHandler(ErrorHandler())
78 p.setEntityResolver(Resolver(path))
79 p.parse(filename)
80 return h.parser.tree
81
82
83 def sexp(node):
84 s = transforms.Sexp()
85 node.dispatch(s)
86 return s.out