blob: e3b7917318e06c15de6ce327bcc147fd2e2466bc [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
Eli Benderskyca4d97e2013-08-25 19:05:55 -0700342 element name, and *attributes* is the element attributes. If
343 :attr:`ordered_attributes` is true, this is a list (see
344 :attr:`ordered_attributes` for a full description). Otherwise it's a
345 dictionary mapping names to values.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347
348.. method:: xmlparser.EndElementHandler(name)
349
350 Called for the end of every element.
351
352
353.. method:: xmlparser.ProcessingInstructionHandler(target, data)
354
355 Called for every processing instruction.
356
357
358.. method:: xmlparser.CharacterDataHandler(data)
359
360 Called for character data. This will be called for normal character data, CDATA
361 marked content, and ignorable whitespace. Applications which must distinguish
362 these cases can use the :attr:`StartCdataSectionHandler`,
363 :attr:`EndCdataSectionHandler`, and :attr:`ElementDeclHandler` callbacks to
364 collect the required information.
365
366
367.. method:: xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName)
368
369 Called for unparsed (NDATA) entity declarations. This is only present for
370 version 1.2 of the Expat library; for more recent versions, use
371 :attr:`EntityDeclHandler` instead. (The underlying function in the Expat
372 library has been declared obsolete.)
373
374
375.. method:: xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)
376
377 Called for all entity declarations. For parameter and internal entities,
378 *value* will be a string giving the declared contents of the entity; this will
379 be ``None`` for external entities. The *notationName* parameter will be
380 ``None`` for parsed entities, and the name of the notation for unparsed
381 entities. *is_parameter_entity* will be true if the entity is a parameter entity
382 or false for general entities (most applications only need to be concerned with
383 general entities). This is only available starting with version 1.95.0 of the
384 Expat library.
385
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387.. method:: xmlparser.NotationDeclHandler(notationName, base, systemId, publicId)
388
389 Called for notation declarations. *notationName*, *base*, and *systemId*, and
390 *publicId* are strings if given. If the public identifier is omitted,
391 *publicId* will be ``None``.
392
393
394.. method:: xmlparser.StartNamespaceDeclHandler(prefix, uri)
395
396 Called when an element contains a namespace declaration. Namespace declarations
397 are processed before the :attr:`StartElementHandler` is called for the element
398 on which declarations are placed.
399
400
401.. method:: xmlparser.EndNamespaceDeclHandler(prefix)
402
403 Called when the closing tag is reached for an element that contained a
404 namespace declaration. This is called once for each namespace declaration on
405 the element in the reverse of the order for which the
406 :attr:`StartNamespaceDeclHandler` was called to indicate the start of each
407 namespace declaration's scope. Calls to this handler are made after the
408 corresponding :attr:`EndElementHandler` for the end of the element.
409
410
411.. method:: xmlparser.CommentHandler(data)
412
413 Called for comments. *data* is the text of the comment, excluding the leading
Ezio Melotti694f2332012-09-20 09:47:03 +0300414 ``'<!-``\ ``-'`` and trailing ``'-``\ ``->'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000415
416
417.. method:: xmlparser.StartCdataSectionHandler()
418
419 Called at the start of a CDATA section. This and :attr:`EndCdataSectionHandler`
420 are needed to be able to identify the syntactical start and end for CDATA
421 sections.
422
423
424.. method:: xmlparser.EndCdataSectionHandler()
425
426 Called at the end of a CDATA section.
427
428
429.. method:: xmlparser.DefaultHandler(data)
430
431 Called for any characters in the XML document for which no applicable handler
432 has been specified. This means characters that are part of a construct which
433 could be reported, but for which no handler has been supplied.
434
435
436.. method:: xmlparser.DefaultHandlerExpand(data)
437
438 This is the same as the :func:`DefaultHandler`, but doesn't inhibit expansion
439 of internal entities. The entity reference will not be passed to the default
440 handler.
441
442
443.. method:: xmlparser.NotStandaloneHandler()
444
445 Called if the XML document hasn't been declared as being a standalone document.
446 This happens when there is an external subset or a reference to a parameter
447 entity, but the XML declaration does not set standalone to ``yes`` in an XML
Georg Brandl7cb13192010-08-03 12:06:29 +0000448 declaration. If this handler returns ``0``, then the parser will raise an
Georg Brandl116aa622007-08-15 14:28:22 +0000449 :const:`XML_ERROR_NOT_STANDALONE` error. If this handler is not set, no
450 exception is raised by the parser for this condition.
451
452
453.. method:: xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId)
454
455 Called for references to external entities. *base* is the current base, as set
456 by a previous call to :meth:`SetBase`. The public and system identifiers,
457 *systemId* and *publicId*, are strings if given; if the public identifier is not
458 given, *publicId* will be ``None``. The *context* value is opaque and should
459 only be used as described below.
460
461 For external entities to be parsed, this handler must be implemented. It is
462 responsible for creating the sub-parser using
463 ``ExternalEntityParserCreate(context)``, initializing it with the appropriate
464 callbacks, and parsing the entity. This handler should return an integer; if it
Georg Brandl7cb13192010-08-03 12:06:29 +0000465 returns ``0``, the parser will raise an
Georg Brandl116aa622007-08-15 14:28:22 +0000466 :const:`XML_ERROR_EXTERNAL_ENTITY_HANDLING` error, otherwise parsing will
467 continue.
468
469 If this handler is not provided, external entities are reported by the
470 :attr:`DefaultHandler` callback, if provided.
471
472
473.. _expaterror-objects:
474
475ExpatError Exceptions
476---------------------
477
478.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
479
480
481:exc:`ExpatError` exceptions have a number of interesting attributes:
482
483
484.. attribute:: ExpatError.code
485
Georg Brandlb4dac712010-10-15 14:46:48 +0000486 Expat's internal error number for the specific error. The
487 :data:`errors.messages` dictionary maps these error numbers to Expat's error
488 messages. For example::
489
490 from xml.parsers.expat import ParserCreate, ExpatError, errors
491
492 p = ParserCreate()
493 try:
494 p.Parse(some_xml_document)
495 except ExpatError as err:
496 print("Error:", errors.messages[err.code])
497
498 The :mod:`errors` module also provides error message constants and a
499 dictionary :data:`~errors.codes` mapping these messages back to the error
500 codes, see below.
Georg Brandl116aa622007-08-15 14:28:22 +0000501
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503.. attribute:: ExpatError.lineno
504
505 Line number on which the error was detected. The first line is numbered ``1``.
506
Georg Brandl116aa622007-08-15 14:28:22 +0000507
508.. attribute:: ExpatError.offset
509
510 Character offset into the line where the error occurred. The first column is
511 numbered ``0``.
512
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514.. _expat-example:
515
516Example
517-------
518
519The following program defines three handlers that just print out their
520arguments. ::
521
522 import xml.parsers.expat
523
524 # 3 handler functions
525 def start_element(name, attrs):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000526 print('Start element:', name, attrs)
Georg Brandl116aa622007-08-15 14:28:22 +0000527 def end_element(name):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000528 print('End element:', name)
Georg Brandl116aa622007-08-15 14:28:22 +0000529 def char_data(data):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000530 print('Character data:', repr(data))
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532 p = xml.parsers.expat.ParserCreate()
533
534 p.StartElementHandler = start_element
535 p.EndElementHandler = end_element
536 p.CharacterDataHandler = char_data
537
538 p.Parse("""<?xml version="1.0"?>
539 <parent id="top"><child1 name="paul">Text goes here</child1>
540 <child2 name="fred">More text</child2>
541 </parent>""", 1)
542
543The output from this program is::
544
545 Start element: parent {'id': 'top'}
546 Start element: child1 {'name': 'paul'}
547 Character data: 'Text goes here'
548 End element: child1
549 Character data: '\n'
550 Start element: child2 {'name': 'fred'}
551 Character data: 'More text'
552 End element: child2
553 Character data: '\n'
554 End element: parent
555
556
557.. _expat-content-models:
558
559Content Model Descriptions
560--------------------------
561
Georg Brandlb4dac712010-10-15 14:46:48 +0000562.. module:: xml.parsers.expat.model
Georg Brandl116aa622007-08-15 14:28:22 +0000563
Georg Brandlb4dac712010-10-15 14:46:48 +0000564.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566Content modules are described using nested tuples. Each tuple contains four
567values: the type, the quantifier, the name, and a tuple of children. Children
568are simply additional content module descriptions.
569
Georg Brandlb4dac712010-10-15 14:46:48 +0000570The values of the first two fields are constants defined in the
571:mod:`xml.parsers.expat.model` module. These constants can be collected in two
Georg Brandl116aa622007-08-15 14:28:22 +0000572groups: the model type group and the quantifier group.
573
574The constants in the model type group are:
575
576
577.. data:: XML_CTYPE_ANY
578 :noindex:
579
580 The element named by the model name was declared to have a content model of
581 ``ANY``.
582
583
584.. data:: XML_CTYPE_CHOICE
585 :noindex:
586
587 The named element allows a choice from a number of options; this is used for
588 content models such as ``(A | B | C)``.
589
590
591.. data:: XML_CTYPE_EMPTY
592 :noindex:
593
594 Elements which are declared to be ``EMPTY`` have this model type.
595
596
597.. data:: XML_CTYPE_MIXED
598 :noindex:
599
600
601.. data:: XML_CTYPE_NAME
602 :noindex:
603
604
605.. data:: XML_CTYPE_SEQ
606 :noindex:
607
608 Models which represent a series of models which follow one after the other are
609 indicated with this model type. This is used for models such as ``(A, B, C)``.
610
611The constants in the quantifier group are:
612
613
614.. data:: XML_CQUANT_NONE
615 :noindex:
616
617 No modifier is given, so it can appear exactly once, as for ``A``.
618
619
620.. data:: XML_CQUANT_OPT
621 :noindex:
622
623 The model is optional: it can appear once or not at all, as for ``A?``.
624
625
626.. data:: XML_CQUANT_PLUS
627 :noindex:
628
629 The model must occur one or more times (like ``A+``).
630
631
632.. data:: XML_CQUANT_REP
633 :noindex:
634
635 The model must occur zero or more times, as for ``A*``.
636
637
638.. _expat-errors:
639
640Expat error constants
641---------------------
642
Georg Brandlb4dac712010-10-15 14:46:48 +0000643.. module:: xml.parsers.expat.errors
Georg Brandl116aa622007-08-15 14:28:22 +0000644
Georg Brandlb4dac712010-10-15 14:46:48 +0000645The following constants are provided in the :mod:`xml.parsers.expat.errors`
646module. These constants are useful in interpreting some of the attributes of
647the :exc:`ExpatError` exception objects raised when an error has occurred.
648Since for backwards compatibility reasons, the constants' value is the error
649*message* and not the numeric error *code*, you do this by comparing its
650:attr:`code` attribute with
651:samp:`errors.codes[errors.XML_ERROR_{CONSTANT_NAME}]`.
652
653The ``errors`` module has the following attributes:
654
655.. data:: codes
656
657 A dictionary mapping numeric error codes to their string descriptions.
658
659 .. versionadded:: 3.2
660
661
662.. data:: messages
663
664 A dictionary mapping string descriptions to their error codes.
665
666 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000667
668
669.. data:: XML_ERROR_ASYNC_ENTITY
Georg Brandl116aa622007-08-15 14:28:22 +0000670
671
672.. data:: XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674 An entity reference in an attribute value referred to an external entity instead
675 of an internal entity.
676
677
678.. data:: XML_ERROR_BAD_CHAR_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000679
680 A character reference referred to a character which is illegal in XML (for
681 example, character ``0``, or '``&#0;``').
682
683
684.. data:: XML_ERROR_BINARY_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000685
686 An entity reference referred to an entity which was declared with a notation, so
687 cannot be parsed.
688
689
690.. data:: XML_ERROR_DUPLICATE_ATTRIBUTE
Georg Brandl116aa622007-08-15 14:28:22 +0000691
692 An attribute was used more than once in a start tag.
693
694
695.. data:: XML_ERROR_INCORRECT_ENCODING
Georg Brandl116aa622007-08-15 14:28:22 +0000696
697
698.. data:: XML_ERROR_INVALID_TOKEN
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700 Raised when an input byte could not properly be assigned to a character; for
701 example, a NUL byte (value ``0``) in a UTF-8 input stream.
702
703
704.. data:: XML_ERROR_JUNK_AFTER_DOC_ELEMENT
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706 Something other than whitespace occurred after the document element.
707
708
709.. data:: XML_ERROR_MISPLACED_XML_PI
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711 An XML declaration was found somewhere other than the start of the input data.
712
713
714.. data:: XML_ERROR_NO_ELEMENTS
Georg Brandl116aa622007-08-15 14:28:22 +0000715
716 The document contains no elements (XML requires all documents to contain exactly
717 one top-level element)..
718
719
720.. data:: XML_ERROR_NO_MEMORY
Georg Brandl116aa622007-08-15 14:28:22 +0000721
722 Expat was not able to allocate memory internally.
723
724
725.. data:: XML_ERROR_PARAM_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000726
727 A parameter entity reference was found where it was not allowed.
728
729
730.. data:: XML_ERROR_PARTIAL_CHAR
Georg Brandl116aa622007-08-15 14:28:22 +0000731
732 An incomplete character was found in the input.
733
734
735.. data:: XML_ERROR_RECURSIVE_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000736
737 An entity reference contained another reference to the same entity; possibly via
738 a different name, and possibly indirectly.
739
740
741.. data:: XML_ERROR_SYNTAX
Georg Brandl116aa622007-08-15 14:28:22 +0000742
743 Some unspecified syntax error was encountered.
744
745
746.. data:: XML_ERROR_TAG_MISMATCH
Georg Brandl116aa622007-08-15 14:28:22 +0000747
748 An end tag did not match the innermost open start tag.
749
750
751.. data:: XML_ERROR_UNCLOSED_TOKEN
Georg Brandl116aa622007-08-15 14:28:22 +0000752
753 Some token (such as a start tag) was not closed before the end of the stream or
754 the next token was encountered.
755
756
757.. data:: XML_ERROR_UNDEFINED_ENTITY
Georg Brandl116aa622007-08-15 14:28:22 +0000758
759 A reference was made to a entity which was not defined.
760
761
762.. data:: XML_ERROR_UNKNOWN_ENCODING
Georg Brandl116aa622007-08-15 14:28:22 +0000763
764 The document encoding is not supported by Expat.
765
766
767.. data:: XML_ERROR_UNCLOSED_CDATA_SECTION
Georg Brandl116aa622007-08-15 14:28:22 +0000768
769 A CDATA marked section was not closed.
770
771
772.. data:: XML_ERROR_EXTERNAL_ENTITY_HANDLING
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774
775.. data:: XML_ERROR_NOT_STANDALONE
Georg Brandl116aa622007-08-15 14:28:22 +0000776
777 The parser determined that the document was not "standalone" though it declared
778 itself to be in the XML declaration, and the :attr:`NotStandaloneHandler` was
779 set and returned ``0``.
780
781
782.. data:: XML_ERROR_UNEXPECTED_STATE
Georg Brandl116aa622007-08-15 14:28:22 +0000783
784
785.. data:: XML_ERROR_ENTITY_DECLARED_IN_PE
Georg Brandl116aa622007-08-15 14:28:22 +0000786
787
788.. data:: XML_ERROR_FEATURE_REQUIRES_XML_DTD
Georg Brandl116aa622007-08-15 14:28:22 +0000789
790 An operation was requested that requires DTD support to be compiled in, but
791 Expat was configured without DTD support. This should never be reported by a
792 standard build of the :mod:`xml.parsers.expat` module.
793
794
795.. data:: XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING
Georg Brandl116aa622007-08-15 14:28:22 +0000796
797 A behavioral change was requested after parsing started that can only be changed
798 before parsing has started. This is (currently) only raised by
799 :meth:`UseForeignDTD`.
800
801
802.. data:: XML_ERROR_UNBOUND_PREFIX
Georg Brandl116aa622007-08-15 14:28:22 +0000803
804 An undeclared prefix was found when namespace processing was enabled.
805
806
807.. data:: XML_ERROR_UNDECLARING_PREFIX
Georg Brandl116aa622007-08-15 14:28:22 +0000808
809 The document attempted to remove the namespace declaration associated with a
810 prefix.
811
812
813.. data:: XML_ERROR_INCOMPLETE_PE
Georg Brandl116aa622007-08-15 14:28:22 +0000814
815 A parameter entity contained incomplete markup.
816
817
818.. data:: XML_ERROR_XML_DECL
Georg Brandl116aa622007-08-15 14:28:22 +0000819
820 The document contained no document element at all.
821
822
823.. data:: XML_ERROR_TEXT_DECL
Georg Brandl116aa622007-08-15 14:28:22 +0000824
825 There was an error parsing a text declaration in an external entity.
826
827
828.. data:: XML_ERROR_PUBLICID
Georg Brandl116aa622007-08-15 14:28:22 +0000829
830 Characters were found in the public id that are not allowed.
831
832
833.. data:: XML_ERROR_SUSPENDED
Georg Brandl116aa622007-08-15 14:28:22 +0000834
835 The requested operation was made on a suspended parser, but isn't allowed. This
836 includes attempts to provide additional input or to stop the parser.
837
838
839.. data:: XML_ERROR_NOT_SUSPENDED
Georg Brandl116aa622007-08-15 14:28:22 +0000840
841 An attempt to resume the parser was made when the parser had not been suspended.
842
843
844.. data:: XML_ERROR_ABORTED
Georg Brandl116aa622007-08-15 14:28:22 +0000845
846 This should not be reported to Python applications.
847
848
849.. data:: XML_ERROR_FINISHED
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851 The requested operation was made on a parser which was finished parsing input,
852 but isn't allowed. This includes attempts to provide additional input or to
853 stop the parser.
854
855
856.. data:: XML_ERROR_SUSPEND_PE
Georg Brandl116aa622007-08-15 14:28:22 +0000857
Christian Heimesb186d002008-03-18 15:15:01 +0000858
859.. rubric:: Footnotes
860
861.. [#] The encoding string included in XML output should conform to the
862 appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
863 not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
864 and http://www.iana.org/assignments/character-sets .
865