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