1 | n/a | """An XML Reader is the SAX 2 name for an XML parser. XML Parsers |
---|
2 | n/a | should be based on this code. """ |
---|
3 | n/a | |
---|
4 | n/a | from . import handler |
---|
5 | n/a | |
---|
6 | n/a | from ._exceptions import SAXNotSupportedException, SAXNotRecognizedException |
---|
7 | n/a | |
---|
8 | n/a | |
---|
9 | n/a | # ===== XMLREADER ===== |
---|
10 | n/a | |
---|
11 | n/a | class XMLReader: |
---|
12 | n/a | """Interface for reading an XML document using callbacks. |
---|
13 | n/a | |
---|
14 | n/a | XMLReader is the interface that an XML parser's SAX2 driver must |
---|
15 | n/a | implement. This interface allows an application to set and query |
---|
16 | n/a | features and properties in the parser, to register event handlers |
---|
17 | n/a | for document processing, and to initiate a document parse. |
---|
18 | n/a | |
---|
19 | n/a | All SAX interfaces are assumed to be synchronous: the parse |
---|
20 | n/a | methods must not return until parsing is complete, and readers |
---|
21 | n/a | must wait for an event-handler callback to return before reporting |
---|
22 | n/a | the next event.""" |
---|
23 | n/a | |
---|
24 | n/a | def __init__(self): |
---|
25 | n/a | self._cont_handler = handler.ContentHandler() |
---|
26 | n/a | self._dtd_handler = handler.DTDHandler() |
---|
27 | n/a | self._ent_handler = handler.EntityResolver() |
---|
28 | n/a | self._err_handler = handler.ErrorHandler() |
---|
29 | n/a | |
---|
30 | n/a | def parse(self, source): |
---|
31 | n/a | "Parse an XML document from a system identifier or an InputSource." |
---|
32 | n/a | raise NotImplementedError("This method must be implemented!") |
---|
33 | n/a | |
---|
34 | n/a | def getContentHandler(self): |
---|
35 | n/a | "Returns the current ContentHandler." |
---|
36 | n/a | return self._cont_handler |
---|
37 | n/a | |
---|
38 | n/a | def setContentHandler(self, handler): |
---|
39 | n/a | "Registers a new object to receive document content events." |
---|
40 | n/a | self._cont_handler = handler |
---|
41 | n/a | |
---|
42 | n/a | def getDTDHandler(self): |
---|
43 | n/a | "Returns the current DTD handler." |
---|
44 | n/a | return self._dtd_handler |
---|
45 | n/a | |
---|
46 | n/a | def setDTDHandler(self, handler): |
---|
47 | n/a | "Register an object to receive basic DTD-related events." |
---|
48 | n/a | self._dtd_handler = handler |
---|
49 | n/a | |
---|
50 | n/a | def getEntityResolver(self): |
---|
51 | n/a | "Returns the current EntityResolver." |
---|
52 | n/a | return self._ent_handler |
---|
53 | n/a | |
---|
54 | n/a | def setEntityResolver(self, resolver): |
---|
55 | n/a | "Register an object to resolve external entities." |
---|
56 | n/a | self._ent_handler = resolver |
---|
57 | n/a | |
---|
58 | n/a | def getErrorHandler(self): |
---|
59 | n/a | "Returns the current ErrorHandler." |
---|
60 | n/a | return self._err_handler |
---|
61 | n/a | |
---|
62 | n/a | def setErrorHandler(self, handler): |
---|
63 | n/a | "Register an object to receive error-message events." |
---|
64 | n/a | self._err_handler = handler |
---|
65 | n/a | |
---|
66 | n/a | def setLocale(self, locale): |
---|
67 | n/a | """Allow an application to set the locale for errors and warnings. |
---|
68 | n/a | |
---|
69 | n/a | SAX parsers are not required to provide localization for errors |
---|
70 | n/a | and warnings; if they cannot support the requested locale, |
---|
71 | n/a | however, they must raise a SAX exception. Applications may |
---|
72 | n/a | request a locale change in the middle of a parse.""" |
---|
73 | n/a | raise SAXNotSupportedException("Locale support not implemented") |
---|
74 | n/a | |
---|
75 | n/a | def getFeature(self, name): |
---|
76 | n/a | "Looks up and returns the state of a SAX2 feature." |
---|
77 | n/a | raise SAXNotRecognizedException("Feature '%s' not recognized" % name) |
---|
78 | n/a | |
---|
79 | n/a | def setFeature(self, name, state): |
---|
80 | n/a | "Sets the state of a SAX2 feature." |
---|
81 | n/a | raise SAXNotRecognizedException("Feature '%s' not recognized" % name) |
---|
82 | n/a | |
---|
83 | n/a | def getProperty(self, name): |
---|
84 | n/a | "Looks up and returns the value of a SAX2 property." |
---|
85 | n/a | raise SAXNotRecognizedException("Property '%s' not recognized" % name) |
---|
86 | n/a | |
---|
87 | n/a | def setProperty(self, name, value): |
---|
88 | n/a | "Sets the value of a SAX2 property." |
---|
89 | n/a | raise SAXNotRecognizedException("Property '%s' not recognized" % name) |
---|
90 | n/a | |
---|
91 | n/a | class IncrementalParser(XMLReader): |
---|
92 | n/a | """This interface adds three extra methods to the XMLReader |
---|
93 | n/a | interface that allow XML parsers to support incremental |
---|
94 | n/a | parsing. Support for this interface is optional, since not all |
---|
95 | n/a | underlying XML parsers support this functionality. |
---|
96 | n/a | |
---|
97 | n/a | When the parser is instantiated it is ready to begin accepting |
---|
98 | n/a | data from the feed method immediately. After parsing has been |
---|
99 | n/a | finished with a call to close the reset method must be called to |
---|
100 | n/a | make the parser ready to accept new data, either from feed or |
---|
101 | n/a | using the parse method. |
---|
102 | n/a | |
---|
103 | n/a | Note that these methods must _not_ be called during parsing, that |
---|
104 | n/a | is, after parse has been called and before it returns. |
---|
105 | n/a | |
---|
106 | n/a | By default, the class also implements the parse method of the XMLReader |
---|
107 | n/a | interface using the feed, close and reset methods of the |
---|
108 | n/a | IncrementalParser interface as a convenience to SAX 2.0 driver |
---|
109 | n/a | writers.""" |
---|
110 | n/a | |
---|
111 | n/a | def __init__(self, bufsize=2**16): |
---|
112 | n/a | self._bufsize = bufsize |
---|
113 | n/a | XMLReader.__init__(self) |
---|
114 | n/a | |
---|
115 | n/a | def parse(self, source): |
---|
116 | n/a | from . import saxutils |
---|
117 | n/a | source = saxutils.prepare_input_source(source) |
---|
118 | n/a | |
---|
119 | n/a | self.prepareParser(source) |
---|
120 | n/a | file = source.getCharacterStream() |
---|
121 | n/a | if file is None: |
---|
122 | n/a | file = source.getByteStream() |
---|
123 | n/a | buffer = file.read(self._bufsize) |
---|
124 | n/a | while buffer: |
---|
125 | n/a | self.feed(buffer) |
---|
126 | n/a | buffer = file.read(self._bufsize) |
---|
127 | n/a | self.close() |
---|
128 | n/a | |
---|
129 | n/a | def feed(self, data): |
---|
130 | n/a | """This method gives the raw XML data in the data parameter to |
---|
131 | n/a | the parser and makes it parse the data, emitting the |
---|
132 | n/a | corresponding events. It is allowed for XML constructs to be |
---|
133 | n/a | split across several calls to feed. |
---|
134 | n/a | |
---|
135 | n/a | feed may raise SAXException.""" |
---|
136 | n/a | raise NotImplementedError("This method must be implemented!") |
---|
137 | n/a | |
---|
138 | n/a | def prepareParser(self, source): |
---|
139 | n/a | """This method is called by the parse implementation to allow |
---|
140 | n/a | the SAX 2.0 driver to prepare itself for parsing.""" |
---|
141 | n/a | raise NotImplementedError("prepareParser must be overridden!") |
---|
142 | n/a | |
---|
143 | n/a | def close(self): |
---|
144 | n/a | """This method is called when the entire XML document has been |
---|
145 | n/a | passed to the parser through the feed method, to notify the |
---|
146 | n/a | parser that there are no more data. This allows the parser to |
---|
147 | n/a | do the final checks on the document and empty the internal |
---|
148 | n/a | data buffer. |
---|
149 | n/a | |
---|
150 | n/a | The parser will not be ready to parse another document until |
---|
151 | n/a | the reset method has been called. |
---|
152 | n/a | |
---|
153 | n/a | close may raise SAXException.""" |
---|
154 | n/a | raise NotImplementedError("This method must be implemented!") |
---|
155 | n/a | |
---|
156 | n/a | def reset(self): |
---|
157 | n/a | """This method is called after close has been called to reset |
---|
158 | n/a | the parser so that it is ready to parse new documents. The |
---|
159 | n/a | results of calling parse or feed after close without calling |
---|
160 | n/a | reset are undefined.""" |
---|
161 | n/a | raise NotImplementedError("This method must be implemented!") |
---|
162 | n/a | |
---|
163 | n/a | # ===== LOCATOR ===== |
---|
164 | n/a | |
---|
165 | n/a | class Locator: |
---|
166 | n/a | """Interface for associating a SAX event with a document |
---|
167 | n/a | location. A locator object will return valid results only during |
---|
168 | n/a | calls to DocumentHandler methods; at any other time, the |
---|
169 | n/a | results are unpredictable.""" |
---|
170 | n/a | |
---|
171 | n/a | def getColumnNumber(self): |
---|
172 | n/a | "Return the column number where the current event ends." |
---|
173 | n/a | return -1 |
---|
174 | n/a | |
---|
175 | n/a | def getLineNumber(self): |
---|
176 | n/a | "Return the line number where the current event ends." |
---|
177 | n/a | return -1 |
---|
178 | n/a | |
---|
179 | n/a | def getPublicId(self): |
---|
180 | n/a | "Return the public identifier for the current event." |
---|
181 | n/a | return None |
---|
182 | n/a | |
---|
183 | n/a | def getSystemId(self): |
---|
184 | n/a | "Return the system identifier for the current event." |
---|
185 | n/a | return None |
---|
186 | n/a | |
---|
187 | n/a | # ===== INPUTSOURCE ===== |
---|
188 | n/a | |
---|
189 | n/a | class InputSource: |
---|
190 | n/a | """Encapsulation of the information needed by the XMLReader to |
---|
191 | n/a | read entities. |
---|
192 | n/a | |
---|
193 | n/a | This class may include information about the public identifier, |
---|
194 | n/a | system identifier, byte stream (possibly with character encoding |
---|
195 | n/a | information) and/or the character stream of an entity. |
---|
196 | n/a | |
---|
197 | n/a | Applications will create objects of this class for use in the |
---|
198 | n/a | XMLReader.parse method and for returning from |
---|
199 | n/a | EntityResolver.resolveEntity. |
---|
200 | n/a | |
---|
201 | n/a | An InputSource belongs to the application, the XMLReader is not |
---|
202 | n/a | allowed to modify InputSource objects passed to it from the |
---|
203 | n/a | application, although it may make copies and modify those.""" |
---|
204 | n/a | |
---|
205 | n/a | def __init__(self, system_id = None): |
---|
206 | n/a | self.__system_id = system_id |
---|
207 | n/a | self.__public_id = None |
---|
208 | n/a | self.__encoding = None |
---|
209 | n/a | self.__bytefile = None |
---|
210 | n/a | self.__charfile = None |
---|
211 | n/a | |
---|
212 | n/a | def setPublicId(self, public_id): |
---|
213 | n/a | "Sets the public identifier of this InputSource." |
---|
214 | n/a | self.__public_id = public_id |
---|
215 | n/a | |
---|
216 | n/a | def getPublicId(self): |
---|
217 | n/a | "Returns the public identifier of this InputSource." |
---|
218 | n/a | return self.__public_id |
---|
219 | n/a | |
---|
220 | n/a | def setSystemId(self, system_id): |
---|
221 | n/a | "Sets the system identifier of this InputSource." |
---|
222 | n/a | self.__system_id = system_id |
---|
223 | n/a | |
---|
224 | n/a | def getSystemId(self): |
---|
225 | n/a | "Returns the system identifier of this InputSource." |
---|
226 | n/a | return self.__system_id |
---|
227 | n/a | |
---|
228 | n/a | def setEncoding(self, encoding): |
---|
229 | n/a | """Sets the character encoding of this InputSource. |
---|
230 | n/a | |
---|
231 | n/a | The encoding must be a string acceptable for an XML encoding |
---|
232 | n/a | declaration (see section 4.3.3 of the XML recommendation). |
---|
233 | n/a | |
---|
234 | n/a | The encoding attribute of the InputSource is ignored if the |
---|
235 | n/a | InputSource also contains a character stream.""" |
---|
236 | n/a | self.__encoding = encoding |
---|
237 | n/a | |
---|
238 | n/a | def getEncoding(self): |
---|
239 | n/a | "Get the character encoding of this InputSource." |
---|
240 | n/a | return self.__encoding |
---|
241 | n/a | |
---|
242 | n/a | def setByteStream(self, bytefile): |
---|
243 | n/a | """Set the byte stream (a Python file-like object which does |
---|
244 | n/a | not perform byte-to-character conversion) for this input |
---|
245 | n/a | source. |
---|
246 | n/a | |
---|
247 | n/a | The SAX parser will ignore this if there is also a character |
---|
248 | n/a | stream specified, but it will use a byte stream in preference |
---|
249 | n/a | to opening a URI connection itself. |
---|
250 | n/a | |
---|
251 | n/a | If the application knows the character encoding of the byte |
---|
252 | n/a | stream, it should set it with the setEncoding method.""" |
---|
253 | n/a | self.__bytefile = bytefile |
---|
254 | n/a | |
---|
255 | n/a | def getByteStream(self): |
---|
256 | n/a | """Get the byte stream for this input source. |
---|
257 | n/a | |
---|
258 | n/a | The getEncoding method will return the character encoding for |
---|
259 | n/a | this byte stream, or None if unknown.""" |
---|
260 | n/a | return self.__bytefile |
---|
261 | n/a | |
---|
262 | n/a | def setCharacterStream(self, charfile): |
---|
263 | n/a | """Set the character stream for this input source. (The stream |
---|
264 | n/a | must be a Python 2.0 Unicode-wrapped file-like that performs |
---|
265 | n/a | conversion to Unicode strings.) |
---|
266 | n/a | |
---|
267 | n/a | If there is a character stream specified, the SAX parser will |
---|
268 | n/a | ignore any byte stream and will not attempt to open a URI |
---|
269 | n/a | connection to the system identifier.""" |
---|
270 | n/a | self.__charfile = charfile |
---|
271 | n/a | |
---|
272 | n/a | def getCharacterStream(self): |
---|
273 | n/a | "Get the character stream for this input source." |
---|
274 | n/a | return self.__charfile |
---|
275 | n/a | |
---|
276 | n/a | # ===== ATTRIBUTESIMPL ===== |
---|
277 | n/a | |
---|
278 | n/a | class AttributesImpl: |
---|
279 | n/a | |
---|
280 | n/a | def __init__(self, attrs): |
---|
281 | n/a | """Non-NS-aware implementation. |
---|
282 | n/a | |
---|
283 | n/a | attrs should be of the form {name : value}.""" |
---|
284 | n/a | self._attrs = attrs |
---|
285 | n/a | |
---|
286 | n/a | def getLength(self): |
---|
287 | n/a | return len(self._attrs) |
---|
288 | n/a | |
---|
289 | n/a | def getType(self, name): |
---|
290 | n/a | return "CDATA" |
---|
291 | n/a | |
---|
292 | n/a | def getValue(self, name): |
---|
293 | n/a | return self._attrs[name] |
---|
294 | n/a | |
---|
295 | n/a | def getValueByQName(self, name): |
---|
296 | n/a | return self._attrs[name] |
---|
297 | n/a | |
---|
298 | n/a | def getNameByQName(self, name): |
---|
299 | n/a | if name not in self._attrs: |
---|
300 | n/a | raise KeyError(name) |
---|
301 | n/a | return name |
---|
302 | n/a | |
---|
303 | n/a | def getQNameByName(self, name): |
---|
304 | n/a | if name not in self._attrs: |
---|
305 | n/a | raise KeyError(name) |
---|
306 | n/a | return name |
---|
307 | n/a | |
---|
308 | n/a | def getNames(self): |
---|
309 | n/a | return list(self._attrs.keys()) |
---|
310 | n/a | |
---|
311 | n/a | def getQNames(self): |
---|
312 | n/a | return list(self._attrs.keys()) |
---|
313 | n/a | |
---|
314 | n/a | def __len__(self): |
---|
315 | n/a | return len(self._attrs) |
---|
316 | n/a | |
---|
317 | n/a | def __getitem__(self, name): |
---|
318 | n/a | return self._attrs[name] |
---|
319 | n/a | |
---|
320 | n/a | def keys(self): |
---|
321 | n/a | return list(self._attrs.keys()) |
---|
322 | n/a | |
---|
323 | n/a | def __contains__(self, name): |
---|
324 | n/a | return name in self._attrs |
---|
325 | n/a | |
---|
326 | n/a | def get(self, name, alternative=None): |
---|
327 | n/a | return self._attrs.get(name, alternative) |
---|
328 | n/a | |
---|
329 | n/a | def copy(self): |
---|
330 | n/a | return self.__class__(self._attrs) |
---|
331 | n/a | |
---|
332 | n/a | def items(self): |
---|
333 | n/a | return list(self._attrs.items()) |
---|
334 | n/a | |
---|
335 | n/a | def values(self): |
---|
336 | n/a | return list(self._attrs.values()) |
---|
337 | n/a | |
---|
338 | n/a | # ===== ATTRIBUTESNSIMPL ===== |
---|
339 | n/a | |
---|
340 | n/a | class AttributesNSImpl(AttributesImpl): |
---|
341 | n/a | |
---|
342 | n/a | def __init__(self, attrs, qnames): |
---|
343 | n/a | """NS-aware implementation. |
---|
344 | n/a | |
---|
345 | n/a | attrs should be of the form {(ns_uri, lname): value, ...}. |
---|
346 | n/a | qnames of the form {(ns_uri, lname): qname, ...}.""" |
---|
347 | n/a | self._attrs = attrs |
---|
348 | n/a | self._qnames = qnames |
---|
349 | n/a | |
---|
350 | n/a | def getValueByQName(self, name): |
---|
351 | n/a | for (nsname, qname) in self._qnames.items(): |
---|
352 | n/a | if qname == name: |
---|
353 | n/a | return self._attrs[nsname] |
---|
354 | n/a | |
---|
355 | n/a | raise KeyError(name) |
---|
356 | n/a | |
---|
357 | n/a | def getNameByQName(self, name): |
---|
358 | n/a | for (nsname, qname) in self._qnames.items(): |
---|
359 | n/a | if qname == name: |
---|
360 | n/a | return nsname |
---|
361 | n/a | |
---|
362 | n/a | raise KeyError(name) |
---|
363 | n/a | |
---|
364 | n/a | def getQNameByName(self, name): |
---|
365 | n/a | return self._qnames[name] |
---|
366 | n/a | |
---|
367 | n/a | def getQNames(self): |
---|
368 | n/a | return list(self._qnames.values()) |
---|
369 | n/a | |
---|
370 | n/a | def copy(self): |
---|
371 | n/a | return self.__class__(self._attrs, self._qnames) |
---|
372 | n/a | |
---|
373 | n/a | |
---|
374 | n/a | def _test(): |
---|
375 | n/a | XMLReader() |
---|
376 | n/a | IncrementalParser() |
---|
377 | n/a | Locator() |
---|
378 | n/a | |
---|
379 | n/a | if __name__ == "__main__": |
---|
380 | n/a | _test() |
---|