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