blob: 861546c2e8752f06b7aea789d0394d214cb1b469 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`xml.parsers.expat` --- Fast XML parsing using Expat
2=========================================================
3
4.. module:: xml.parsers.expat
5 :synopsis: An interface to the Expat non-validating XML parser.
6.. moduleauthor:: Paul Prescod <paul@prescod.net>
7
8
Christian Heimes5b5e81c2007-12-31 16:14:33 +00009.. Markup notes:
10
11 Many of the attributes of the XMLParser objects are callbacks. Since
12 signature information must be presented, these are described using the method
13 directive. Since they are attributes which are set by client code, in-text
14 references to these attributes should be marked using the :member: role.
15
Georg Brandl116aa622007-08-15 14:28:22 +000016
Georg Brandl116aa622007-08-15 14:28:22 +000017.. index:: single: Expat
18
19The :mod:`xml.parsers.expat` module is a Python interface to the Expat
20non-validating XML parser. The module provides a single extension type,
21:class:`xmlparser`, that represents the current state of an XML parser. After
22an :class:`xmlparser` object has been created, various attributes of the object
23can be set to handler functions. When an XML document is then fed to the
24parser, the handler functions are called for the character data and markup in
25the XML document.
26
27.. index:: module: pyexpat
28
29This module uses the :mod:`pyexpat` module to provide access to the Expat
30parser. Direct use of the :mod:`pyexpat` module is deprecated.
31
32This module provides one exception and one type object:
33
34
35.. exception:: ExpatError
36
37 The exception raised when Expat reports an error. See section
38 :ref:`expaterror-objects` for more information on interpreting Expat errors.
39
40
41.. exception:: error
42
43 Alias for :exc:`ExpatError`.
44
45
46.. data:: XMLParserType
47
48 The type of the return values from the :func:`ParserCreate` function.
49
50The :mod:`xml.parsers.expat` module contains two functions:
51
52
53.. function:: ErrorString(errno)
54
55 Returns an explanatory string for a given error number *errno*.
56
57
Georg Brandl18244152009-09-02 20:34:52 +000058.. function:: ParserCreate(encoding=None, namespace_separator=None)
Georg Brandl116aa622007-08-15 14:28:22 +000059
60 Creates and returns a new :class:`xmlparser` object. *encoding*, if specified,
61 must be a string naming the encoding used by the XML data. Expat doesn't
62 support as many encodings as Python does, and its repertoire of encodings can't
63 be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII. If
Christian Heimesb186d002008-03-18 15:15:01 +000064 *encoding* [1]_ is given it will override the implicit or explicit encoding of the
Georg Brandl116aa622007-08-15 14:28:22 +000065 document.
66
67 Expat can optionally do XML namespace processing for you, enabled by providing a
68 value for *namespace_separator*. The value must be a one-character string; a
69 :exc:`ValueError` will be raised if the string has an illegal length (``None``
70 is considered the same as omission). When namespace processing is enabled,
71 element type names and attribute names that belong to a namespace will be
72 expanded. The element name passed to the element handlers
73 :attr:`StartElementHandler` and :attr:`EndElementHandler` will be the
74 concatenation of the namespace URI, the namespace separator character, and the
75 local part of the name. If the namespace separator is a zero byte (``chr(0)``)
76 then the namespace URI and the local part will be concatenated without any
77 separator.
78
79 For example, if *namespace_separator* is set to a space character (``' '``) and
80 the following document is parsed::
81
82 <?xml version="1.0"?>
83 <root xmlns = "http://default-namespace.org/"
84 xmlns:py = "http://www.python.org/ns/">
85 <py:elem1 />
86 <elem2 xmlns="" />
87 </root>
88
89 :attr:`StartElementHandler` will receive the following strings for each
90 element::
91
92 http://default-namespace.org/ root
93 http://www.python.org/ns/ elem1
94 elem2
95
96
97.. seealso::
98
99 `The Expat XML Parser <http://www.libexpat.org/>`_
100 Home page of the Expat project.
101
102
103.. _xmlparser-objects:
104
105XMLParser Objects
106-----------------
107
108:class:`xmlparser` objects have the following methods:
109
110
111.. method:: xmlparser.Parse(data[, isfinal])
112
113 Parses the contents of the string *data*, calling the appropriate handler
114 functions to process the parsed data. *isfinal* must be true on the final call
115 to this method. *data* can be the empty string at any time.
116
117
118.. method:: xmlparser.ParseFile(file)
119
120 Parse XML data reading from the object *file*. *file* only needs to provide
121 the ``read(nbytes)`` method, returning the empty string when there's no more
122 data.
123
124
125.. method:: xmlparser.SetBase(base)
126
127 Sets the base to be used for resolving relative URIs in system identifiers in
128 declarations. Resolving relative identifiers is left to the application: this
129 value will be passed through as the *base* argument to the
130 :func:`ExternalEntityRefHandler`, :func:`NotationDeclHandler`, and
131 :func:`UnparsedEntityDeclHandler` functions.
132
133
134.. method:: xmlparser.GetBase()
135
136 Returns a string containing the base set by a previous call to :meth:`SetBase`,
137 or ``None`` if :meth:`SetBase` hasn't been called.
138
139
140.. method:: xmlparser.GetInputContext()
141
142 Returns the input data that generated the current event as a string. The data is
143 in the encoding of the entity which contains the text. When called while an
144 event handler is not active, the return value is ``None``.
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147.. method:: xmlparser.ExternalEntityParserCreate(context[, encoding])
148
149 Create a "child" parser which can be used to parse an external parsed entity
150 referred to by content parsed by the parent parser. The *context* parameter
151 should be the string passed to the :meth:`ExternalEntityRefHandler` handler
152 function, described below. The child parser is created with the
153 :attr:`ordered_attributes` and :attr:`specified_attributes` set to the values of
154 this parser.
155
Antoine Pitroua83878e2011-01-05 18:37:22 +0000156.. method:: xmlparser.SetParamEntityParsing(flag)
157
158 Control parsing of parameter entities (including the external DTD subset).
159 Possible *flag* values are :const:`XML_PARAM_ENTITY_PARSING_NEVER`,
160 :const:`XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE` and
161 :const:`XML_PARAM_ENTITY_PARSING_ALWAYS`. Return true if setting the flag
162 was successful.
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164.. method:: xmlparser.UseForeignDTD([flag])
165
166 Calling this with a true value for *flag* (the default) will cause Expat to call
167 the :attr:`ExternalEntityRefHandler` with :const:`None` for all arguments to
168 allow an alternate DTD to be loaded. If the document does not contain a
169 document type declaration, the :attr:`ExternalEntityRefHandler` will still be
170 called, but the :attr:`StartDoctypeDeclHandler` and
171 :attr:`EndDoctypeDeclHandler` will not be called.
172
173 Passing a false value for *flag* will cancel a previous call that passed a true
174 value, but otherwise has no effect.
175
176 This method can only be called before the :meth:`Parse` or :meth:`ParseFile`
177 methods are called; calling it after either of those have been called causes
178 :exc:`ExpatError` to be raised with the :attr:`code` attribute set to
Georg Brandlb4dac712010-10-15 14:46:48 +0000179 ``errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000180
Georg Brandl116aa622007-08-15 14:28:22 +0000181:class:`xmlparser` objects have the following attributes:
182
183
184.. attribute:: xmlparser.buffer_size
185
Georg Brandl48310cd2009-01-03 21:18:54 +0000186 The size of the buffer used when :attr:`buffer_text` is true.
187 A new buffer size can be set by assigning a new integer value
188 to this attribute.
Christian Heimes2380ac72008-01-09 00:17:24 +0000189 When the size is changed, the buffer will be flushed.
190
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192.. attribute:: xmlparser.buffer_text
193
194 Setting this to true causes the :class:`xmlparser` object to buffer textual
195 content returned by Expat to avoid multiple calls to the
196 :meth:`CharacterDataHandler` callback whenever possible. This can improve
197 performance substantially since Expat normally breaks character data into chunks
198 at every line ending. This attribute is false by default, and may be changed at
199 any time.
200
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202.. attribute:: xmlparser.buffer_used
203
204 If :attr:`buffer_text` is enabled, the number of bytes stored in the buffer.
205 These bytes represent UTF-8 encoded text. This attribute has no meaningful
206 interpretation when :attr:`buffer_text` is false.
207
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209.. attribute:: xmlparser.ordered_attributes
210
211 Setting this attribute to a non-zero integer causes the attributes to be
212 reported as a list rather than a dictionary. The attributes are presented in
213 the order found in the document text. For each attribute, two list entries are
214 presented: the attribute name and the attribute value. (Older versions of this
215 module also used this format.) By default, this attribute is false; it may be
216 changed at any time.
217
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219.. attribute:: xmlparser.specified_attributes
220
221 If set to a non-zero integer, the parser will report only those attributes which
222 were specified in the document instance and not those which were derived from
223 attribute declarations. Applications which set this need to be especially
224 careful to use what additional information is available from the declarations as
225 needed to comply with the standards for the behavior of XML processors. By
226 default, this attribute is false; it may be changed at any time.
227
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229The following attributes contain values relating to the most recent error
230encountered by an :class:`xmlparser` object, and will only have correct values
231once a call to :meth:`Parse` or :meth:`ParseFile` has raised a
232:exc:`xml.parsers.expat.ExpatError` exception.
233
234
235.. attribute:: xmlparser.ErrorByteIndex
236
237 Byte index at which an error occurred.
238
239
240.. attribute:: xmlparser.ErrorCode
241
242 Numeric code specifying the problem. This value can be passed to the
243 :func:`ErrorString` function, or compared to one of the constants defined in the
244 ``errors`` object.
245
246
247.. attribute:: xmlparser.ErrorColumnNumber
248
249 Column number at which an error occurred.
250
251
252.. attribute:: xmlparser.ErrorLineNumber
253
254 Line number at which an error occurred.
255
256The following attributes contain values relating to the current parse location
257in an :class:`xmlparser` object. During a callback reporting a parse event they
258indicate the location of the first of the sequence of characters that generated
259the event. When called outside of a callback, the position indicated will be
260just past the last parse event (regardless of whether there was an associated
261callback).
262
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264.. attribute:: xmlparser.CurrentByteIndex
265
266 Current byte index in the parser input.
267
268
269.. attribute:: xmlparser.CurrentColumnNumber
270
271 Current column number in the parser input.
272
273
274.. attribute:: xmlparser.CurrentLineNumber
275
276 Current line number in the parser input.
277
278Here is the list of handlers that can be set. To set a handler on an
279:class:`xmlparser` object *o*, use ``o.handlername = func``. *handlername* must
280be taken from the following list, and *func* must be a callable object accepting
281the correct number of arguments. The arguments are all strings, unless
282otherwise stated.
283
284
285.. method:: xmlparser.XmlDeclHandler(version, encoding, standalone)
286
287 Called when the XML declaration is parsed. The XML declaration is the
288 (optional) declaration of the applicable version of the XML recommendation, the
289 encoding of the document text, and an optional "standalone" declaration.
290 *version* and *encoding* will be strings, and *standalone* will be ``1`` if the
291 document is declared standalone, ``0`` if it is declared not to be standalone,
292 or ``-1`` if the standalone clause was omitted. This is only available with
293 Expat version 1.95.0 or newer.
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296.. method:: xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset)
297
298 Called when Expat begins parsing the document type declaration (``<!DOCTYPE
299 ...``). The *doctypeName* is provided exactly as presented. The *systemId* and
300 *publicId* parameters give the system and public identifiers if specified, or
301 ``None`` if omitted. *has_internal_subset* will be true if the document
302 contains and internal document declaration subset. This requires Expat version
303 1.2 or newer.
304
305
306.. method:: xmlparser.EndDoctypeDeclHandler()
307
308 Called when Expat is done parsing the document type declaration. This requires
309 Expat version 1.2 or newer.
310
311
312.. method:: xmlparser.ElementDeclHandler(name, model)
313
314 Called once for each element type declaration. *name* is the name of the
315 element type, and *model* is a representation of the content model.
316
317
318.. method:: xmlparser.AttlistDeclHandler(elname, attname, type, default, required)
319
320 Called for each declared attribute for an element type. If an attribute list
321 declaration declares three attributes, this handler is called three times, once
322 for each attribute. *elname* is the name of the element to which the
323 declaration applies and *attname* is the name of the attribute declared. The
324 attribute type is a string passed as *type*; the possible values are
325 ``'CDATA'``, ``'ID'``, ``'IDREF'``, ... *default* gives the default value for
326 the attribute used when the attribute is not specified by the document instance,
327 or ``None`` if there is no default value (``#IMPLIED`` values). If the
328 attribute is required to be given in the document instance, *required* will be
329 true. This requires Expat version 1.95.0 or newer.
330
331
332.. method:: xmlparser.StartElementHandler(name, attributes)
333
334 Called for the start of every element. *name* is a string containing the
335 element name, and *attributes* is a dictionary mapping attribute names to their
336 values.
337
338
339.. method:: xmlparser.EndElementHandler(name)
340
341 Called for the end of every element.
342
343
344.. method:: xmlparser.ProcessingInstructionHandler(target, data)
345
346 Called for every processing instruction.
347
348
349.. method:: xmlparser.CharacterDataHandler(data)
350
351 Called for character data. This will be called for normal character data, CDATA
352 marked content, and ignorable whitespace. Applications which must distinguish
353 these cases can use the :attr:`StartCdataSectionHandler`,
354 :attr:`EndCdataSectionHandler`, and :attr:`ElementDeclHandler` callbacks to
355 collect the required information.
356
357
358.. method:: xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName)
359
360 Called for unparsed (NDATA) entity declarations. This is only present for
361 version 1.2 of the Expat library; for more recent versions, use
362 :attr:`EntityDeclHandler` instead. (The underlying function in the Expat
363 library has been declared obsolete.)
364
365
366.. method:: xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)
367
368 Called for all entity declarations. For parameter and internal entities,
369 *value* will be a string giving the declared contents of the entity; this will
370 be ``None`` for external entities. The *notationName* parameter will be
371 ``None`` for parsed entities, and the name of the notation for unparsed
372 entities. *is_parameter_entity* will be true if the entity is a parameter entity
373 or false for general entities (most applications only need to be concerned with
374 general entities). This is only available starting with version 1.95.0 of the
375 Expat library.
376
Georg Brandl116aa622007-08-15 14:28:22 +0000377
378.. method:: xmlparser.NotationDeclHandler(notationName, base, systemId, publicId)
379
380 Called for notation declarations. *notationName*, *base*, and *systemId*, and
381 *publicId* are strings if given. If the public identifier is omitted,
382 *publicId* will be ``None``.
383
384
385.. method:: xmlparser.StartNamespaceDeclHandler(prefix, uri)
386
387 Called when an element contains a namespace declaration. Namespace declarations
388 are processed before the :attr:`StartElementHandler` is called for the element
389 on which declarations are placed.
390
391
392.. method:: xmlparser.EndNamespaceDeclHandler(prefix)
393
394 Called when the closing tag is reached for an element that contained a
395 namespace declaration. This is called once for each namespace declaration on
396 the element in the reverse of the order for which the
397 :attr:`StartNamespaceDeclHandler` was called to indicate the start of each
398 namespace declaration's scope. Calls to this handler are made after the
399 corresponding :attr:`EndElementHandler` for the end of the element.
400
401
402.. method:: xmlparser.CommentHandler(data)
403
404 Called for comments. *data* is the text of the comment, excluding the leading
Ezio Melotti694f2332012-09-20 09:47:03 +0300405 ``'<!-``\ ``-'`` and trailing ``'-``\ ``->'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407
408.. method:: xmlparser.StartCdataSectionHandler()
409
410 Called at the start of a CDATA section. This and :attr:`EndCdataSectionHandler`
411 are needed to be able to identify the syntactical start and end for CDATA
412 sections.
413
414
415.. method:: xmlparser.EndCdataSectionHandler()
416
417 Called at the end of a CDATA section.
418
419
420.. method:: xmlparser.DefaultHandler(data)
421
422 Called for any characters in the XML document for which no applicable handler
423 has been specified. This means characters that are part of a construct which
424 could be reported, but for which no handler has been supplied.
425
426
427.. method:: xmlparser.DefaultHandlerExpand(data)
428
429 This is the same as the :func:`DefaultHandler`, but doesn't inhibit expansion
430 of internal entities. The entity reference will not be passed to the default
431 handler.
432
433
434.. method:: xmlparser.NotStandaloneHandler()
435
436 Called if the XML document hasn't been declared as being a standalone document.
437 This happens when there is an external subset or a reference to a parameter
438 entity, but the XML declaration does not set standalone to ``yes`` in an XML
Georg Brandl7cb13192010-08-03 12:06:29 +0000439 declaration. If this handler returns ``0``, then the parser will raise an
Georg Brandl116aa622007-08-15 14:28:22 +0000440 :const:`XML_ERROR_NOT_STANDALONE` error. If this handler is not set, no
441 exception is raised by the parser for this condition.
442
443
444.. method:: xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId)
445
446 Called for references to external entities. *base* is the current base, as set
447 by a previous call to :meth:`SetBase`. The public and system identifiers,
448 *systemId* and *publicId*, are strings if given; if the public identifier is not
449 given, *publicId* will be ``None``. The *context* value is opaque and should
450 only be used as described below.
451
452 For external entities to be parsed, this handler must be implemented. It is
453 responsible for creating the sub-parser using
454 ``ExternalEntityParserCreate(context)``, initializing it with the appropriate
455 callbacks, and parsing the entity. This handler should return an integer; if it
Georg Brandl7cb13192010-08-03 12:06:29 +0000456 returns ``0``, the parser will raise an
Georg Brandl116aa622007-08-15 14:28:22 +0000457 :const:`XML_ERROR_EXTERNAL_ENTITY_HANDLING` error, otherwise parsing will
458 continue.
459
460 If this handler is not provided, external entities are reported by the
461 :attr:`DefaultHandler` callback, if provided.
462
463
464.. _expaterror-objects:
465
466ExpatError Exceptions
467---------------------
468
469.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
470
471
472:exc:`ExpatError` exceptions have a number of interesting attributes:
473
474
475.. attribute:: ExpatError.code
476
Georg Brandlb4dac712010-10-15 14:46:48 +0000477 Expat's internal error number for the specific error. The
478 :data:`errors.messages` dictionary maps these error numbers to Expat's error
479 messages. For example::
480
481 from xml.parsers.expat import ParserCreate, ExpatError, errors
482
483 p = ParserCreate()
484 try:
485 p.Parse(some_xml_document)
486 except ExpatError as err:
487 print("Error:", errors.messages[err.code])
488
489 The :mod:`errors` module also provides error message constants and a
490 dictionary :data:`~errors.codes` mapping these messages back to the error
491 codes, see below.
Georg Brandl116aa622007-08-15 14:28:22 +0000492
Georg Brandl116aa622007-08-15 14:28:22 +0000493
494.. attribute:: ExpatError.lineno
495
496 Line number on which the error was detected. The first line is numbered ``1``.
497
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499.. attribute:: ExpatError.offset
500
501 Character offset into the line where the error occurred. The first column is
502 numbered ``0``.
503
Georg Brandl116aa622007-08-15 14:28:22 +0000504
505.. _expat-example:
506
507Example
508-------
509
510The following program defines three handlers that just print out their
511arguments. ::
512
513 import xml.parsers.expat
514
515 # 3 handler functions
516 def start_element(name, attrs):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000517 print('Start element:', name, attrs)
Georg Brandl116aa622007-08-15 14:28:22 +0000518 def end_element(name):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000519 print('End element:', name)
Georg Brandl116aa622007-08-15 14:28:22 +0000520 def char_data(data):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000521 print('Character data:', repr(data))
Georg Brandl116aa622007-08-15 14:28:22 +0000522
523 p = xml.parsers.expat.ParserCreate()
524
525 p.StartElementHandler = start_element
526 p.EndElementHandler = end_element
527 p.CharacterDataHandler = char_data
528
529 p.Parse("""<?xml version="1.0"?>
530 <parent id="top"><child1 name="paul">Text goes here</child1>
531 <child2 name="fred">More text</child2>
532 </parent>""", 1)
533
534The output from this program is::
535
536 Start element: parent {'id': 'top'}
537 Start element: child1 {'name': 'paul'}
538 Character data: 'Text goes here'
539 End element: child1
540 Character data: '\n'
541 Start element: child2 {'name': 'fred'}
542 Character data: 'More text'
543 End element: child2
544 Character data: '\n'
545 End element: parent
546
547
548.. _expat-content-models:
549
550Content Model Descriptions
551--------------------------
552
Georg Brandlb4dac712010-10-15 14:46:48 +0000553.. module:: xml.parsers.expat.model
Georg Brandl116aa622007-08-15 14:28:22 +0000554
Georg Brandlb4dac712010-10-15 14:46:48 +0000555.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557Content modules are described using nested tuples. Each tuple contains four
558values: the type, the quantifier, the name, and a tuple of children. Children
559are simply additional content module descriptions.
560
Georg Brandlb4dac712010-10-15 14:46:48 +0000561The values of the first two fields are constants defined in the
562:mod:`xml.parsers.expat.model` module. These constants can be collected in two
Georg Brandl116aa622007-08-15 14:28:22 +0000563groups: the model type group and the quantifier group.
564
565The constants in the model type group are:
566
567
568.. data:: XML_CTYPE_ANY
569 :noindex:
570
571 The element named by the model name was declared to have a content model of
572 ``ANY``.
573
574
575.. data:: XML_CTYPE_CHOICE
576 :noindex:
577
578 The named element allows a choice from a number of options; this is used for
579 content models such as ``(A | B | C)``.
580
581
582.. data:: XML_CTYPE_EMPTY
583 :noindex:
584
585 Elements which are declared to be ``EMPTY`` have this model type.
586
587
588.. data:: XML_CTYPE_MIXED
589 :noindex:
590
591
592.. data:: XML_CTYPE_NAME
593 :noindex:
594
595
596.. data:: XML_CTYPE_SEQ
597 :noindex:
598
599 Models which represent a series of models which follow one after the other are
600 indicated with this model type. This is used for models such as ``(A, B, C)``.
601
602The constants in the quantifier group are:
603
604
605.. data:: XML_CQUANT_NONE
606 :noindex:
607
608 No modifier is given, so it can appear exactly once, as for ``A``.
609
610
611.. data:: XML_CQUANT_OPT
612 :noindex:
613
614 The model is optional: it can appear once or not at all, as for ``A?``.
615
616
617.. data:: XML_CQUANT_PLUS
618 :noindex:
619
620 The model must occur one or more times (like ``A+``).
621
622
623.. data:: XML_CQUANT_REP
624 :noindex:
625
626 The model must occur zero or more times, as for ``A*``.
627
628
629.. _expat-errors:
630
631Expat error constants
632---------------------
633
Georg Brandlb4dac712010-10-15 14:46:48 +0000634.. module:: xml.parsers.expat.errors
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Georg Brandlb4dac712010-10-15 14:46:48 +0000636The following constants are provided in the :mod:`xml.parsers.expat.errors`
637module. These constants are useful in interpreting some of the attributes of
638the :exc:`ExpatError` exception objects raised when an error has occurred.
639Since for backwards compatibility reasons, the constants' value is the error
640*message* and not the numeric error *code*, you do this by comparing its
641:attr:`code` attribute with
642:samp:`errors.codes[errors.XML_ERROR_{CONSTANT_NAME}]`.
643
644The ``errors`` module has the following attributes:
645
646.. data:: codes
647
648 A dictionary mapping numeric error codes to their string descriptions.
649
650 .. versionadded:: 3.2
651
652
653.. data:: messages
654
655 A dictionary mapping string descriptions to their error codes.
656
657 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000658
659
660.. data:: XML_ERROR_ASYNC_ENTITY
Georg Brandl116aa622007-08-15 14:28:22 +0000661
662
663.. data:: XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665 An entity reference in an attribute value referred to an external entity instead
666 of an internal entity.
667
668
669.. data:: XML_ERROR_BAD_CHAR_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000670
671 A character reference referred to a character which is illegal in XML (for
672 example, character ``0``, or '``&#0;``').
673
674
675.. data:: XML_ERROR_BINARY_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000676
677 An entity reference referred to an entity which was declared with a notation, so
678 cannot be parsed.
679
680
681.. data:: XML_ERROR_DUPLICATE_ATTRIBUTE
Georg Brandl116aa622007-08-15 14:28:22 +0000682
683 An attribute was used more than once in a start tag.
684
685
686.. data:: XML_ERROR_INCORRECT_ENCODING
Georg Brandl116aa622007-08-15 14:28:22 +0000687
688
689.. data:: XML_ERROR_INVALID_TOKEN
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691 Raised when an input byte could not properly be assigned to a character; for
692 example, a NUL byte (value ``0``) in a UTF-8 input stream.
693
694
695.. data:: XML_ERROR_JUNK_AFTER_DOC_ELEMENT
Georg Brandl116aa622007-08-15 14:28:22 +0000696
697 Something other than whitespace occurred after the document element.
698
699
700.. data:: XML_ERROR_MISPLACED_XML_PI
Georg Brandl116aa622007-08-15 14:28:22 +0000701
702 An XML declaration was found somewhere other than the start of the input data.
703
704
705.. data:: XML_ERROR_NO_ELEMENTS
Georg Brandl116aa622007-08-15 14:28:22 +0000706
707 The document contains no elements (XML requires all documents to contain exactly
708 one top-level element)..
709
710
711.. data:: XML_ERROR_NO_MEMORY
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713 Expat was not able to allocate memory internally.
714
715
716.. data:: XML_ERROR_PARAM_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718 A parameter entity reference was found where it was not allowed.
719
720
721.. data:: XML_ERROR_PARTIAL_CHAR
Georg Brandl116aa622007-08-15 14:28:22 +0000722
723 An incomplete character was found in the input.
724
725
726.. data:: XML_ERROR_RECURSIVE_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000727
728 An entity reference contained another reference to the same entity; possibly via
729 a different name, and possibly indirectly.
730
731
732.. data:: XML_ERROR_SYNTAX
Georg Brandl116aa622007-08-15 14:28:22 +0000733
734 Some unspecified syntax error was encountered.
735
736
737.. data:: XML_ERROR_TAG_MISMATCH
Georg Brandl116aa622007-08-15 14:28:22 +0000738
739 An end tag did not match the innermost open start tag.
740
741
742.. data:: XML_ERROR_UNCLOSED_TOKEN
Georg Brandl116aa622007-08-15 14:28:22 +0000743
744 Some token (such as a start tag) was not closed before the end of the stream or
745 the next token was encountered.
746
747
748.. data:: XML_ERROR_UNDEFINED_ENTITY
Georg Brandl116aa622007-08-15 14:28:22 +0000749
750 A reference was made to a entity which was not defined.
751
752
753.. data:: XML_ERROR_UNKNOWN_ENCODING
Georg Brandl116aa622007-08-15 14:28:22 +0000754
755 The document encoding is not supported by Expat.
756
757
758.. data:: XML_ERROR_UNCLOSED_CDATA_SECTION
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760 A CDATA marked section was not closed.
761
762
763.. data:: XML_ERROR_EXTERNAL_ENTITY_HANDLING
Georg Brandl116aa622007-08-15 14:28:22 +0000764
765
766.. data:: XML_ERROR_NOT_STANDALONE
Georg Brandl116aa622007-08-15 14:28:22 +0000767
768 The parser determined that the document was not "standalone" though it declared
769 itself to be in the XML declaration, and the :attr:`NotStandaloneHandler` was
770 set and returned ``0``.
771
772
773.. data:: XML_ERROR_UNEXPECTED_STATE
Georg Brandl116aa622007-08-15 14:28:22 +0000774
775
776.. data:: XML_ERROR_ENTITY_DECLARED_IN_PE
Georg Brandl116aa622007-08-15 14:28:22 +0000777
778
779.. data:: XML_ERROR_FEATURE_REQUIRES_XML_DTD
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781 An operation was requested that requires DTD support to be compiled in, but
782 Expat was configured without DTD support. This should never be reported by a
783 standard build of the :mod:`xml.parsers.expat` module.
784
785
786.. data:: XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788 A behavioral change was requested after parsing started that can only be changed
789 before parsing has started. This is (currently) only raised by
790 :meth:`UseForeignDTD`.
791
792
793.. data:: XML_ERROR_UNBOUND_PREFIX
Georg Brandl116aa622007-08-15 14:28:22 +0000794
795 An undeclared prefix was found when namespace processing was enabled.
796
797
798.. data:: XML_ERROR_UNDECLARING_PREFIX
Georg Brandl116aa622007-08-15 14:28:22 +0000799
800 The document attempted to remove the namespace declaration associated with a
801 prefix.
802
803
804.. data:: XML_ERROR_INCOMPLETE_PE
Georg Brandl116aa622007-08-15 14:28:22 +0000805
806 A parameter entity contained incomplete markup.
807
808
809.. data:: XML_ERROR_XML_DECL
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811 The document contained no document element at all.
812
813
814.. data:: XML_ERROR_TEXT_DECL
Georg Brandl116aa622007-08-15 14:28:22 +0000815
816 There was an error parsing a text declaration in an external entity.
817
818
819.. data:: XML_ERROR_PUBLICID
Georg Brandl116aa622007-08-15 14:28:22 +0000820
821 Characters were found in the public id that are not allowed.
822
823
824.. data:: XML_ERROR_SUSPENDED
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826 The requested operation was made on a suspended parser, but isn't allowed. This
827 includes attempts to provide additional input or to stop the parser.
828
829
830.. data:: XML_ERROR_NOT_SUSPENDED
Georg Brandl116aa622007-08-15 14:28:22 +0000831
832 An attempt to resume the parser was made when the parser had not been suspended.
833
834
835.. data:: XML_ERROR_ABORTED
Georg Brandl116aa622007-08-15 14:28:22 +0000836
837 This should not be reported to Python applications.
838
839
840.. data:: XML_ERROR_FINISHED
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842 The requested operation was made on a parser which was finished parsing input,
843 but isn't allowed. This includes attempts to provide additional input or to
844 stop the parser.
845
846
847.. data:: XML_ERROR_SUSPEND_PE
Georg Brandl116aa622007-08-15 14:28:22 +0000848
Christian Heimesb186d002008-03-18 15:15:01 +0000849
850.. rubric:: Footnotes
851
852.. [#] The encoding string included in XML output should conform to the
853 appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
854 not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
855 and http://www.iana.org/assignments/character-sets .
856