Debian Codegraph @

Doc/library/xml.sax.handler.rst

raw
1 :mod:`!xml.sax.handler` --- Base classes for SAX handlers
2 =========================================================
3
4 .. module:: xml.sax.handler
5 :synopsis: Base classes for SAX event handlers.
6
7 .. moduleauthor:: Lars Marius Garshol <[email protected]>
8 .. sectionauthor:: Martin v. Löwis <[email protected]>
9
10 **Source code:** :source:`Lib/xml/sax/handler.py`
11
12 --------------
13
14 The SAX API defines five kinds of handlers: content handlers, DTD handlers,
15 error handlers, entity resolvers and lexical handlers. Applications normally
16 only need to implement those interfaces whose events they are interested in;
17 they can implement the interfaces in a single object or in multiple objects.
18 Handler implementations should inherit from the base classes provided in the
19 module :mod:`!xml.sax.handler`, so that all methods get default implementations.
20
21
22 .. class:: ContentHandler
23
24 This is the main callback interface in SAX, and the one most important to
25 applications. The order of events in this interface mirrors the order of the
26 information in the document.
27
28
29 .. class:: DTDHandler
30
31 Handle DTD events.
32
33 This interface specifies only those DTD events required for basic parsing
34 (unparsed entities and attributes).
35
36
37 .. class:: EntityResolver
38
39 Basic interface for resolving entities. If you create an object implementing
40 this interface, then register the object with your Parser, the parser will call
41 the method in your object to resolve all external entities.
42
43
44 .. class:: ErrorHandler
45
46 Interface used by the parser to present error and warning messages to the
47 application. The methods of this object control whether errors are immediately
48 converted to exceptions or are handled in some other way.
49
50
51 .. class:: LexicalHandler
52
53 Interface used by the parser to represent low frequency events which may not
54 be of interest to many applications.
55
56 In addition to these classes, :mod:`!xml.sax.handler` provides symbolic constants
57 for the feature and property names.
58
59
60 .. data:: feature_namespaces
61
62 | value: ``"http://xml.org/sax/features/namespaces"``
63 | true: Perform Namespace processing.
64 | false: Optionally do not perform Namespace processing (implies
65 namespace-prefixes; default).
66 | access: (parsing) read-only; (not parsing) read/write
67
68
69 .. data:: feature_namespace_prefixes
70
71 | value: ``"http://xml.org/sax/features/namespace-prefixes"``
72 | true: Report the original prefixed names and attributes used for Namespace
73 declarations.
74 | false: Do not report attributes used for Namespace declarations, and
75 optionally do not report original prefixed names (default).
76 | access: (parsing) read-only; (not parsing) read/write
77
78
79 .. data:: feature_string_interning
80
81 | value: ``"http://xml.org/sax/features/string-interning"``
82 | true: All element names, prefixes, attribute names, Namespace URIs, and
83 local names are interned using the built-in intern function.
84 | false: Names are not necessarily interned, although they may be (default).
85 | access: (parsing) read-only; (not parsing) read/write
86
87
88 .. data:: feature_validation
89
90 | value: ``"http://xml.org/sax/features/validation"``
91 | true: Report all validation errors (implies external-general-entities and
92 external-parameter-entities).
93 | false: Do not report validation errors.
94 | access: (parsing) read-only; (not parsing) read/write
95
96
97 .. data:: feature_external_ges
98
99 .. warning::
100
101 Enabling opens a vulnerability to
102 `external entity attacks <https://en.wikipedia.org/wiki/XML_external_entity_attack>`_
103 if the parser is used with user-provided XML content.
104 Please reflect on your `threat model <https://en.wikipedia.org/wiki/Threat_model>`_
105 before enabling this feature.
106
107 | value: ``"http://xml.org/sax/features/external-general-entities"``
108 | true: Include all external general (text) entities.
109 | false: Do not include external general entities.
110 | access: (parsing) read-only; (not parsing) read/write
111
112
113 .. data:: feature_external_pes
114
115 | value: ``"http://xml.org/sax/features/external-parameter-entities"``
116 | true: Include all external parameter entities, including the external DTD
117 subset.
118 | false: Do not include any external parameter entities, even the external
119 DTD subset.
120 | access: (parsing) read-only; (not parsing) read/write
121
122
123 .. data:: all_features
124
125 List of all features.
126
127
128 .. data:: property_lexical_handler
129
130 | value: ``"http://xml.org/sax/properties/lexical-handler"``
131 | data type: xml.sax.handler.LexicalHandler (not supported in Python 2)
132 | description: An optional extension handler for lexical events like
133 comments.
134 | access: read/write
135
136
137 .. data:: property_declaration_handler
138
139 | value: ``"http://xml.org/sax/properties/declaration-handler"``
140 | data type: xml.sax.sax2lib.DeclHandler (not supported in Python 2)
141 | description: An optional extension handler for DTD-related events other
142 than notations and unparsed entities.
143 | access: read/write
144
145
146 .. data:: property_dom_node
147
148 | value: ``"http://xml.org/sax/properties/dom-node"``
149 | data type: org.w3c.dom.Node (not supported in Python 2)
150 | description: When parsing, the current DOM node being visited if this is
151 a DOM iterator; when not parsing, the root DOM node for iteration.
152 | access: (parsing) read-only; (not parsing) read/write
153
154
155 .. data:: property_xml_string
156
157 | value: ``"http://xml.org/sax/properties/xml-string"``
158 | data type: Bytes
159 | description: The literal string of characters that was the source for the
160 current event.
161 | access: read-only
162
163
164 .. data:: all_properties
165
166 List of all known property names.
167
168
169 .. _content-handler-objects:
170
171 ContentHandler Objects
172 ----------------------
173
174 Users are expected to subclass :class:`ContentHandler` to support their
175 application. The following methods are called by the parser on the appropriate
176 events in the input document:
177
178
179 .. method:: ContentHandler.setDocumentLocator(locator)
180
181 Called by the parser to give the application a locator for locating the origin
182 of document events.
183
184 SAX parsers are strongly encouraged (though not absolutely required) to supply a
185 locator: if it does so, it must supply the locator to the application by
186 invoking this method before invoking any of the other methods in the
187 DocumentHandler interface.
188
189 The locator allows the application to determine the end position of any
190 document-related event, even if the parser is not reporting an error. Typically,
191 the application will use this information for reporting its own errors (such as
192 character content that does not match an application's business rules). The
193 information returned by the locator is probably not sufficient for use with a
194 search engine.
195
196 Note that the locator will return correct information only during the invocation
197 of the events in this interface. The application should not attempt to use it at
198 any other time.
199
200
201 .. method:: ContentHandler.startDocument()
202
203 Receive notification of the beginning of a document.
204
205 The SAX parser will invoke this method only once, before any other methods in
206 this interface or in DTDHandler (except for :meth:`setDocumentLocator`).
207
208
209 .. method:: ContentHandler.endDocument()
210
211 Receive notification of the end of a document.
212
213 The SAX parser will invoke this method only once, and it will be the last method
214 invoked during the parse. The parser shall not invoke this method until it has
215 either abandoned parsing (because of an unrecoverable error) or reached the end
216 of input.
217
218
219 .. method:: ContentHandler.startPrefixMapping(prefix, uri)
220
221 Begin the scope of a prefix-URI Namespace mapping.
222
223 The information from this event is not necessary for normal Namespace
224 processing: the SAX XML reader will automatically replace prefixes for element
225 and attribute names when the ``feature_namespaces`` feature is enabled (the
226 default).
227
228 There are cases, however, when applications need to use prefixes in character
229 data or in attribute values, where they cannot safely be expanded automatically;
230 the :meth:`startPrefixMapping` and :meth:`endPrefixMapping` events supply the
231 information to the application to expand prefixes in those contexts itself, if
232 necessary.
233
234 .. XXX This is not really the default, is it? MvL
235
236 Note that :meth:`startPrefixMapping` and :meth:`endPrefixMapping` events are not
237 guaranteed to be properly nested relative to each-other: all
238 :meth:`startPrefixMapping` events will occur before the corresponding
239 :meth:`startElement` event, and all :meth:`endPrefixMapping` events will occur
240 after the corresponding :meth:`endElement` event, but their order is not
241 guaranteed.
242
243
244 .. method:: ContentHandler.endPrefixMapping(prefix)
245
246 End the scope of a prefix-URI mapping.
247
248 See :meth:`startPrefixMapping` for details. This event will always occur after
249 the corresponding :meth:`endElement` event, but the order of
250 :meth:`endPrefixMapping` events is not otherwise guaranteed.
251
252
253 .. method:: ContentHandler.startElement(name, attrs)
254
255 Signals the start of an element in non-namespace mode.
256
257 The *name* parameter contains the raw XML 1.0 name of the element type as a
258 string and the *attrs* parameter holds an object of the
259 :ref:`Attributes <attributes-objects>` interface containing the attributes of
260 the element. The object passed as *attrs* may be re-used by the parser; holding
261 on to a reference to it is not a reliable way to keep a copy of the attributes.
262 To keep a copy of the attributes, use the :meth:`copy` method of the *attrs*
263 object.
264
265
266 .. method:: ContentHandler.endElement(name)
267
268 Signals the end of an element in non-namespace mode.
269
270 The *name* parameter contains the name of the element type, just as with the
271 :meth:`startElement` event.
272
273
274 .. method:: ContentHandler.startElementNS(name, qname, attrs)
275
276 Signals the start of an element in namespace mode.
277
278 The *name* parameter contains the name of the element type as a ``(uri,
279 localname)`` tuple, the *qname* parameter contains the raw XML 1.0 name used in
280 the source document, and the *attrs* parameter holds an instance of the
281 :ref:`AttributesNS <attributes-ns-objects>` interface
282 containing the attributes of the element. If no namespace is associated with
283 the element, the *uri* component of *name* will be ``None``. The object passed
284 as *attrs* may be re-used by the parser; holding on to a reference to it is not
285 a reliable way to keep a copy of the attributes. To keep a copy of the
286 attributes, use the :meth:`copy` method of the *attrs* object.
287
288 Parsers may set the *qname* parameter to ``None``, unless the
289 ``feature_namespace_prefixes`` feature is activated.
290
291
292 .. method:: ContentHandler.endElementNS(name, qname)
293
294 Signals the end of an element in namespace mode.
295
296 The *name* parameter contains the name of the element type, just as with the
297 :meth:`startElementNS` method, likewise the *qname* parameter.
298
299
300 .. method:: ContentHandler.characters(content)
301
302 Receive notification of character data.
303
304 The Parser will call this method to report each chunk of character data. SAX
305 parsers may return all contiguous character data in a single chunk, or they may
306 split it into several chunks; however, all of the characters in any single event
307 must come from the same external entity so that the Locator provides useful
308 information.
309
310 *content* may be a string or bytes instance; the ``expat`` reader module
311 always produces strings.
312
313 .. note::
314
315 The earlier SAX 1 interface provided by the Python XML Special Interest Group
316 used a more Java-like interface for this method. Since most parsers used from
317 Python did not take advantage of the older interface, the simpler signature was
318 chosen to replace it. To convert old code to the new interface, use *content*
319 instead of slicing content with the old *offset* and *length* parameters.
320
321
322 .. method:: ContentHandler.ignorableWhitespace(whitespace)
323
324 Receive notification of ignorable whitespace in element content.
325
326 Validating Parsers must use this method to report each chunk of ignorable
327 whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating
328 parsers may also use this method if they are capable of parsing and using
329 content models.
330
331 SAX parsers may return all contiguous whitespace in a single chunk, or they may
332 split it into several chunks; however, all of the characters in any single event
333 must come from the same external entity, so that the Locator provides useful
334 information.
335
336
337 .. method:: ContentHandler.processingInstruction(target, data)
338
339 Receive notification of a processing instruction.
340
341 The Parser will invoke this method once for each processing instruction found:
342 note that processing instructions may occur before or after the main document
343 element.
344
345 A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a
346 text declaration (XML 1.0, section 4.3.1) using this method.
347
348
349 .. method:: ContentHandler.skippedEntity(name)
350
351 Receive notification of a skipped entity.
352
353 The Parser will invoke this method once for each entity skipped. Non-validating
354 processors may skip entities if they have not seen the declarations (because,
355 for example, the entity was declared in an external DTD subset). All processors
356 may skip external entities, depending on the values of the
357 ``feature_external_ges`` and the ``feature_external_pes`` properties.
358
359
360 .. _dtd-handler-objects:
361
362 DTDHandler Objects
363 ------------------
364
365 :class:`DTDHandler` instances provide the following methods:
366
367
368 .. method:: DTDHandler.notationDecl(name, publicId, systemId)
369
370 Handle a notation declaration event.
371
372
373 .. method:: DTDHandler.unparsedEntityDecl(name, publicId, systemId, ndata)
374
375 Handle an unparsed entity declaration event.
376
377
378 .. _entity-resolver-objects:
379
380 EntityResolver Objects
381 ----------------------
382
383
384 .. method:: EntityResolver.resolveEntity(publicId, systemId)
385
386 Resolve the system identifier of an entity and return either the system
387 identifier to read from as a string, or an InputSource to read from. The default
388 implementation returns *systemId*.
389
390
391 .. _sax-error-handler:
392
393 ErrorHandler Objects
394 --------------------
395
396 Objects with this interface are used to receive error and warning information
397 from the :class:`~xml.sax.xmlreader.XMLReader`. If you create an object that
398 implements this interface, then register the object with your
399 :class:`~xml.sax.xmlreader.XMLReader`, the parser
400 will call the methods in your object to report all warnings and errors. There
401 are three levels of errors available: warnings, (possibly) recoverable errors,
402 and unrecoverable errors. All methods take a :exc:`~xml.sax.SAXParseException` as the
403 only parameter. Errors and warnings may be converted to an exception by raising
404 the passed-in exception object.
405
406
407 .. method:: ErrorHandler.error(exception)
408
409 Called when the parser encounters a recoverable error. If this method does not
410 raise an exception, parsing may continue, but further document information
411 should not be expected by the application. Allowing the parser to continue may
412 allow additional errors to be discovered in the input document.
413
414
415 .. method:: ErrorHandler.fatalError(exception)
416
417 Called when the parser encounters an error it cannot recover from; parsing is
418 expected to terminate when this method returns.
419
420
421 .. method:: ErrorHandler.warning(exception)
422
423 Called when the parser presents minor warning information to the application.
424 Parsing is expected to continue when this method returns, and document
425 information will continue to be passed to the application. Raising an exception
426 in this method will cause parsing to end.
427
428
429 .. _lexical-handler-objects:
430
431 LexicalHandler Objects
432 ----------------------
433 Optional SAX2 handler for lexical events.
434
435 This handler is used to obtain lexical information about an XML
436 document. Lexical information includes information describing the
437 document encoding used and XML comments embedded in the document, as
438 well as section boundaries for the DTD and for any CDATA sections.
439 The lexical handlers are used in the same manner as content handlers.
440
441 Set the LexicalHandler of an XMLReader by using the setProperty method
442 with the property identifier
443 ``'http://xml.org/sax/properties/lexical-handler'``.
444
445
446 .. method:: LexicalHandler.comment(content)
447
448 Reports a comment anywhere in the document (including the DTD and
449 outside the document element).
450
451 .. method:: LexicalHandler.startDTD(name, public_id, system_id)
452
453 Reports the start of the DTD declarations if the document has an
454 associated DTD.
455
456 .. method:: LexicalHandler.endDTD()
457
458 Reports the end of DTD declaration.
459
460 .. method:: LexicalHandler.startCDATA()
461
462 Reports the start of a CDATA marked section.
463
464 The contents of the CDATA marked section will be reported through
465 the characters handler.
466
467 .. method:: LexicalHandler.endCDATA()
468
469 Reports the end of a CDATA marked section.