1 | n/a | """\ |
---|
2 | n/a | A library of useful helper classes to the SAX classes, for the |
---|
3 | n/a | convenience of application and driver writers. |
---|
4 | n/a | """ |
---|
5 | n/a | |
---|
6 | n/a | import os, urllib.parse, urllib.request |
---|
7 | n/a | import io |
---|
8 | n/a | import codecs |
---|
9 | n/a | from . import handler |
---|
10 | n/a | from . import xmlreader |
---|
11 | n/a | |
---|
12 | n/a | def __dict_replace(s, d): |
---|
13 | n/a | """Replace substrings of a string using a dictionary.""" |
---|
14 | n/a | for key, value in d.items(): |
---|
15 | n/a | s = s.replace(key, value) |
---|
16 | n/a | return s |
---|
17 | n/a | |
---|
18 | n/a | def escape(data, entities={}): |
---|
19 | n/a | """Escape &, <, and > in a string of data. |
---|
20 | n/a | |
---|
21 | n/a | You can escape other strings of data by passing a dictionary as |
---|
22 | n/a | the optional entities parameter. The keys and values must all be |
---|
23 | n/a | strings; each key will be replaced with its corresponding value. |
---|
24 | n/a | """ |
---|
25 | n/a | |
---|
26 | n/a | # must do ampersand first |
---|
27 | n/a | data = data.replace("&", "&") |
---|
28 | n/a | data = data.replace(">", ">") |
---|
29 | n/a | data = data.replace("<", "<") |
---|
30 | n/a | if entities: |
---|
31 | n/a | data = __dict_replace(data, entities) |
---|
32 | n/a | return data |
---|
33 | n/a | |
---|
34 | n/a | def unescape(data, entities={}): |
---|
35 | n/a | """Unescape &, <, and > in a string of data. |
---|
36 | n/a | |
---|
37 | n/a | You can unescape other strings of data by passing a dictionary as |
---|
38 | n/a | the optional entities parameter. The keys and values must all be |
---|
39 | n/a | strings; each key will be replaced with its corresponding value. |
---|
40 | n/a | """ |
---|
41 | n/a | data = data.replace("<", "<") |
---|
42 | n/a | data = data.replace(">", ">") |
---|
43 | n/a | if entities: |
---|
44 | n/a | data = __dict_replace(data, entities) |
---|
45 | n/a | # must do ampersand last |
---|
46 | n/a | return data.replace("&", "&") |
---|
47 | n/a | |
---|
48 | n/a | def quoteattr(data, entities={}): |
---|
49 | n/a | """Escape and quote an attribute value. |
---|
50 | n/a | |
---|
51 | n/a | Escape &, <, and > in a string of data, then quote it for use as |
---|
52 | n/a | an attribute value. The \" character will be escaped as well, if |
---|
53 | n/a | necessary. |
---|
54 | n/a | |
---|
55 | n/a | You can escape other strings of data by passing a dictionary as |
---|
56 | n/a | the optional entities parameter. The keys and values must all be |
---|
57 | n/a | strings; each key will be replaced with its corresponding value. |
---|
58 | n/a | """ |
---|
59 | n/a | entities = entities.copy() |
---|
60 | n/a | entities.update({'\n': ' ', '\r': ' ', '\t':'	'}) |
---|
61 | n/a | data = escape(data, entities) |
---|
62 | n/a | if '"' in data: |
---|
63 | n/a | if "'" in data: |
---|
64 | n/a | data = '"%s"' % data.replace('"', """) |
---|
65 | n/a | else: |
---|
66 | n/a | data = "'%s'" % data |
---|
67 | n/a | else: |
---|
68 | n/a | data = '"%s"' % data |
---|
69 | n/a | return data |
---|
70 | n/a | |
---|
71 | n/a | |
---|
72 | n/a | def _gettextwriter(out, encoding): |
---|
73 | n/a | if out is None: |
---|
74 | n/a | import sys |
---|
75 | n/a | return sys.stdout |
---|
76 | n/a | |
---|
77 | n/a | if isinstance(out, io.TextIOBase): |
---|
78 | n/a | # use a text writer as is |
---|
79 | n/a | return out |
---|
80 | n/a | |
---|
81 | n/a | if isinstance(out, (codecs.StreamWriter, codecs.StreamReaderWriter)): |
---|
82 | n/a | # use a codecs stream writer as is |
---|
83 | n/a | return out |
---|
84 | n/a | |
---|
85 | n/a | # wrap a binary writer with TextIOWrapper |
---|
86 | n/a | if isinstance(out, io.RawIOBase): |
---|
87 | n/a | # Keep the original file open when the TextIOWrapper is |
---|
88 | n/a | # destroyed |
---|
89 | n/a | class _wrapper: |
---|
90 | n/a | __class__ = out.__class__ |
---|
91 | n/a | def __getattr__(self, name): |
---|
92 | n/a | return getattr(out, name) |
---|
93 | n/a | buffer = _wrapper() |
---|
94 | n/a | buffer.close = lambda: None |
---|
95 | n/a | else: |
---|
96 | n/a | # This is to handle passed objects that aren't in the |
---|
97 | n/a | # IOBase hierarchy, but just have a write method |
---|
98 | n/a | buffer = io.BufferedIOBase() |
---|
99 | n/a | buffer.writable = lambda: True |
---|
100 | n/a | buffer.write = out.write |
---|
101 | n/a | try: |
---|
102 | n/a | # TextIOWrapper uses this methods to determine |
---|
103 | n/a | # if BOM (for UTF-16, etc) should be added |
---|
104 | n/a | buffer.seekable = out.seekable |
---|
105 | n/a | buffer.tell = out.tell |
---|
106 | n/a | except AttributeError: |
---|
107 | n/a | pass |
---|
108 | n/a | return io.TextIOWrapper(buffer, encoding=encoding, |
---|
109 | n/a | errors='xmlcharrefreplace', |
---|
110 | n/a | newline='\n', |
---|
111 | n/a | write_through=True) |
---|
112 | n/a | |
---|
113 | n/a | class XMLGenerator(handler.ContentHandler): |
---|
114 | n/a | |
---|
115 | n/a | def __init__(self, out=None, encoding="iso-8859-1", short_empty_elements=False): |
---|
116 | n/a | handler.ContentHandler.__init__(self) |
---|
117 | n/a | out = _gettextwriter(out, encoding) |
---|
118 | n/a | self._write = out.write |
---|
119 | n/a | self._flush = out.flush |
---|
120 | n/a | self._ns_contexts = [{}] # contains uri -> prefix dicts |
---|
121 | n/a | self._current_context = self._ns_contexts[-1] |
---|
122 | n/a | self._undeclared_ns_maps = [] |
---|
123 | n/a | self._encoding = encoding |
---|
124 | n/a | self._short_empty_elements = short_empty_elements |
---|
125 | n/a | self._pending_start_element = False |
---|
126 | n/a | |
---|
127 | n/a | def _qname(self, name): |
---|
128 | n/a | """Builds a qualified name from a (ns_url, localname) pair""" |
---|
129 | n/a | if name[0]: |
---|
130 | n/a | # Per http://www.w3.org/XML/1998/namespace, The 'xml' prefix is |
---|
131 | n/a | # bound by definition to http://www.w3.org/XML/1998/namespace. It |
---|
132 | n/a | # does not need to be declared and will not usually be found in |
---|
133 | n/a | # self._current_context. |
---|
134 | n/a | if 'http://www.w3.org/XML/1998/namespace' == name[0]: |
---|
135 | n/a | return 'xml:' + name[1] |
---|
136 | n/a | # The name is in a non-empty namespace |
---|
137 | n/a | prefix = self._current_context[name[0]] |
---|
138 | n/a | if prefix: |
---|
139 | n/a | # If it is not the default namespace, prepend the prefix |
---|
140 | n/a | return prefix + ":" + name[1] |
---|
141 | n/a | # Return the unqualified name |
---|
142 | n/a | return name[1] |
---|
143 | n/a | |
---|
144 | n/a | def _finish_pending_start_element(self,endElement=False): |
---|
145 | n/a | if self._pending_start_element: |
---|
146 | n/a | self._write('>') |
---|
147 | n/a | self._pending_start_element = False |
---|
148 | n/a | |
---|
149 | n/a | # ContentHandler methods |
---|
150 | n/a | |
---|
151 | n/a | def startDocument(self): |
---|
152 | n/a | self._write('<?xml version="1.0" encoding="%s"?>\n' % |
---|
153 | n/a | self._encoding) |
---|
154 | n/a | |
---|
155 | n/a | def endDocument(self): |
---|
156 | n/a | self._flush() |
---|
157 | n/a | |
---|
158 | n/a | def startPrefixMapping(self, prefix, uri): |
---|
159 | n/a | self._ns_contexts.append(self._current_context.copy()) |
---|
160 | n/a | self._current_context[uri] = prefix |
---|
161 | n/a | self._undeclared_ns_maps.append((prefix, uri)) |
---|
162 | n/a | |
---|
163 | n/a | def endPrefixMapping(self, prefix): |
---|
164 | n/a | self._current_context = self._ns_contexts[-1] |
---|
165 | n/a | del self._ns_contexts[-1] |
---|
166 | n/a | |
---|
167 | n/a | def startElement(self, name, attrs): |
---|
168 | n/a | self._finish_pending_start_element() |
---|
169 | n/a | self._write('<' + name) |
---|
170 | n/a | for (name, value) in attrs.items(): |
---|
171 | n/a | self._write(' %s=%s' % (name, quoteattr(value))) |
---|
172 | n/a | if self._short_empty_elements: |
---|
173 | n/a | self._pending_start_element = True |
---|
174 | n/a | else: |
---|
175 | n/a | self._write(">") |
---|
176 | n/a | |
---|
177 | n/a | def endElement(self, name): |
---|
178 | n/a | if self._pending_start_element: |
---|
179 | n/a | self._write('/>') |
---|
180 | n/a | self._pending_start_element = False |
---|
181 | n/a | else: |
---|
182 | n/a | self._write('</%s>' % name) |
---|
183 | n/a | |
---|
184 | n/a | def startElementNS(self, name, qname, attrs): |
---|
185 | n/a | self._finish_pending_start_element() |
---|
186 | n/a | self._write('<' + self._qname(name)) |
---|
187 | n/a | |
---|
188 | n/a | for prefix, uri in self._undeclared_ns_maps: |
---|
189 | n/a | if prefix: |
---|
190 | n/a | self._write(' xmlns:%s="%s"' % (prefix, uri)) |
---|
191 | n/a | else: |
---|
192 | n/a | self._write(' xmlns="%s"' % uri) |
---|
193 | n/a | self._undeclared_ns_maps = [] |
---|
194 | n/a | |
---|
195 | n/a | for (name, value) in attrs.items(): |
---|
196 | n/a | self._write(' %s=%s' % (self._qname(name), quoteattr(value))) |
---|
197 | n/a | if self._short_empty_elements: |
---|
198 | n/a | self._pending_start_element = True |
---|
199 | n/a | else: |
---|
200 | n/a | self._write(">") |
---|
201 | n/a | |
---|
202 | n/a | def endElementNS(self, name, qname): |
---|
203 | n/a | if self._pending_start_element: |
---|
204 | n/a | self._write('/>') |
---|
205 | n/a | self._pending_start_element = False |
---|
206 | n/a | else: |
---|
207 | n/a | self._write('</%s>' % self._qname(name)) |
---|
208 | n/a | |
---|
209 | n/a | def characters(self, content): |
---|
210 | n/a | if content: |
---|
211 | n/a | self._finish_pending_start_element() |
---|
212 | n/a | if not isinstance(content, str): |
---|
213 | n/a | content = str(content, self._encoding) |
---|
214 | n/a | self._write(escape(content)) |
---|
215 | n/a | |
---|
216 | n/a | def ignorableWhitespace(self, content): |
---|
217 | n/a | if content: |
---|
218 | n/a | self._finish_pending_start_element() |
---|
219 | n/a | if not isinstance(content, str): |
---|
220 | n/a | content = str(content, self._encoding) |
---|
221 | n/a | self._write(content) |
---|
222 | n/a | |
---|
223 | n/a | def processingInstruction(self, target, data): |
---|
224 | n/a | self._finish_pending_start_element() |
---|
225 | n/a | self._write('<?%s %s?>' % (target, data)) |
---|
226 | n/a | |
---|
227 | n/a | |
---|
228 | n/a | class XMLFilterBase(xmlreader.XMLReader): |
---|
229 | n/a | """This class is designed to sit between an XMLReader and the |
---|
230 | n/a | client application's event handlers. By default, it does nothing |
---|
231 | n/a | but pass requests up to the reader and events on to the handlers |
---|
232 | n/a | unmodified, but subclasses can override specific methods to modify |
---|
233 | n/a | the event stream or the configuration requests as they pass |
---|
234 | n/a | through.""" |
---|
235 | n/a | |
---|
236 | n/a | def __init__(self, parent = None): |
---|
237 | n/a | xmlreader.XMLReader.__init__(self) |
---|
238 | n/a | self._parent = parent |
---|
239 | n/a | |
---|
240 | n/a | # ErrorHandler methods |
---|
241 | n/a | |
---|
242 | n/a | def error(self, exception): |
---|
243 | n/a | self._err_handler.error(exception) |
---|
244 | n/a | |
---|
245 | n/a | def fatalError(self, exception): |
---|
246 | n/a | self._err_handler.fatalError(exception) |
---|
247 | n/a | |
---|
248 | n/a | def warning(self, exception): |
---|
249 | n/a | self._err_handler.warning(exception) |
---|
250 | n/a | |
---|
251 | n/a | # ContentHandler methods |
---|
252 | n/a | |
---|
253 | n/a | def setDocumentLocator(self, locator): |
---|
254 | n/a | self._cont_handler.setDocumentLocator(locator) |
---|
255 | n/a | |
---|
256 | n/a | def startDocument(self): |
---|
257 | n/a | self._cont_handler.startDocument() |
---|
258 | n/a | |
---|
259 | n/a | def endDocument(self): |
---|
260 | n/a | self._cont_handler.endDocument() |
---|
261 | n/a | |
---|
262 | n/a | def startPrefixMapping(self, prefix, uri): |
---|
263 | n/a | self._cont_handler.startPrefixMapping(prefix, uri) |
---|
264 | n/a | |
---|
265 | n/a | def endPrefixMapping(self, prefix): |
---|
266 | n/a | self._cont_handler.endPrefixMapping(prefix) |
---|
267 | n/a | |
---|
268 | n/a | def startElement(self, name, attrs): |
---|
269 | n/a | self._cont_handler.startElement(name, attrs) |
---|
270 | n/a | |
---|
271 | n/a | def endElement(self, name): |
---|
272 | n/a | self._cont_handler.endElement(name) |
---|
273 | n/a | |
---|
274 | n/a | def startElementNS(self, name, qname, attrs): |
---|
275 | n/a | self._cont_handler.startElementNS(name, qname, attrs) |
---|
276 | n/a | |
---|
277 | n/a | def endElementNS(self, name, qname): |
---|
278 | n/a | self._cont_handler.endElementNS(name, qname) |
---|
279 | n/a | |
---|
280 | n/a | def characters(self, content): |
---|
281 | n/a | self._cont_handler.characters(content) |
---|
282 | n/a | |
---|
283 | n/a | def ignorableWhitespace(self, chars): |
---|
284 | n/a | self._cont_handler.ignorableWhitespace(chars) |
---|
285 | n/a | |
---|
286 | n/a | def processingInstruction(self, target, data): |
---|
287 | n/a | self._cont_handler.processingInstruction(target, data) |
---|
288 | n/a | |
---|
289 | n/a | def skippedEntity(self, name): |
---|
290 | n/a | self._cont_handler.skippedEntity(name) |
---|
291 | n/a | |
---|
292 | n/a | # DTDHandler methods |
---|
293 | n/a | |
---|
294 | n/a | def notationDecl(self, name, publicId, systemId): |
---|
295 | n/a | self._dtd_handler.notationDecl(name, publicId, systemId) |
---|
296 | n/a | |
---|
297 | n/a | def unparsedEntityDecl(self, name, publicId, systemId, ndata): |
---|
298 | n/a | self._dtd_handler.unparsedEntityDecl(name, publicId, systemId, ndata) |
---|
299 | n/a | |
---|
300 | n/a | # EntityResolver methods |
---|
301 | n/a | |
---|
302 | n/a | def resolveEntity(self, publicId, systemId): |
---|
303 | n/a | return self._ent_handler.resolveEntity(publicId, systemId) |
---|
304 | n/a | |
---|
305 | n/a | # XMLReader methods |
---|
306 | n/a | |
---|
307 | n/a | def parse(self, source): |
---|
308 | n/a | self._parent.setContentHandler(self) |
---|
309 | n/a | self._parent.setErrorHandler(self) |
---|
310 | n/a | self._parent.setEntityResolver(self) |
---|
311 | n/a | self._parent.setDTDHandler(self) |
---|
312 | n/a | self._parent.parse(source) |
---|
313 | n/a | |
---|
314 | n/a | def setLocale(self, locale): |
---|
315 | n/a | self._parent.setLocale(locale) |
---|
316 | n/a | |
---|
317 | n/a | def getFeature(self, name): |
---|
318 | n/a | return self._parent.getFeature(name) |
---|
319 | n/a | |
---|
320 | n/a | def setFeature(self, name, state): |
---|
321 | n/a | self._parent.setFeature(name, state) |
---|
322 | n/a | |
---|
323 | n/a | def getProperty(self, name): |
---|
324 | n/a | return self._parent.getProperty(name) |
---|
325 | n/a | |
---|
326 | n/a | def setProperty(self, name, value): |
---|
327 | n/a | self._parent.setProperty(name, value) |
---|
328 | n/a | |
---|
329 | n/a | # XMLFilter methods |
---|
330 | n/a | |
---|
331 | n/a | def getParent(self): |
---|
332 | n/a | return self._parent |
---|
333 | n/a | |
---|
334 | n/a | def setParent(self, parent): |
---|
335 | n/a | self._parent = parent |
---|
336 | n/a | |
---|
337 | n/a | # --- Utility functions |
---|
338 | n/a | |
---|
339 | n/a | def prepare_input_source(source, base=""): |
---|
340 | n/a | """This function takes an InputSource and an optional base URL and |
---|
341 | n/a | returns a fully resolved InputSource object ready for reading.""" |
---|
342 | n/a | |
---|
343 | n/a | if isinstance(source, str): |
---|
344 | n/a | source = xmlreader.InputSource(source) |
---|
345 | n/a | elif hasattr(source, "read"): |
---|
346 | n/a | f = source |
---|
347 | n/a | source = xmlreader.InputSource() |
---|
348 | n/a | if isinstance(f.read(0), str): |
---|
349 | n/a | source.setCharacterStream(f) |
---|
350 | n/a | else: |
---|
351 | n/a | source.setByteStream(f) |
---|
352 | n/a | if hasattr(f, "name") and isinstance(f.name, str): |
---|
353 | n/a | source.setSystemId(f.name) |
---|
354 | n/a | |
---|
355 | n/a | if source.getCharacterStream() is None and source.getByteStream() is None: |
---|
356 | n/a | sysid = source.getSystemId() |
---|
357 | n/a | basehead = os.path.dirname(os.path.normpath(base)) |
---|
358 | n/a | sysidfilename = os.path.join(basehead, sysid) |
---|
359 | n/a | if os.path.isfile(sysidfilename): |
---|
360 | n/a | source.setSystemId(sysidfilename) |
---|
361 | n/a | f = open(sysidfilename, "rb") |
---|
362 | n/a | else: |
---|
363 | n/a | source.setSystemId(urllib.parse.urljoin(base, sysid)) |
---|
364 | n/a | f = urllib.request.urlopen(source.getSystemId()) |
---|
365 | n/a | |
---|
366 | n/a | source.setByteStream(f) |
---|
367 | n/a | |
---|
368 | n/a | return source |
---|