blob: 620ffb1cd4cb4a5287de04c6dbe56046440d09d5 [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
Ned Deilye7d532f2014-03-27 16:39:58 -0700103 Due to limitations in the ``Expat`` library used by :mod:`pyexpat`,
104 the :class:`xmlparser` instance returned can only be used to parse a single
105 XML document. Call ``ParserCreate`` for each document to provide unique
106 parser instances.
107
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109.. seealso::
110
111 `The Expat XML Parser <http://www.libexpat.org/>`_
112 Home page of the Expat project.
113
114
115.. _xmlparser-objects:
116
117XMLParser Objects
118-----------------
119
120:class:`xmlparser` objects have the following methods:
121
122
123.. method:: xmlparser.Parse(data[, isfinal])
124
125 Parses the contents of the string *data*, calling the appropriate handler
126 functions to process the parsed data. *isfinal* must be true on the final call
Ned Deilye7d532f2014-03-27 16:39:58 -0700127 to this method; it allows the parsing of a single file in fragments,
128 not the submission of multiple files.
129 *data* can be the empty string at any time.
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131
132.. method:: xmlparser.ParseFile(file)
133
134 Parse XML data reading from the object *file*. *file* only needs to provide
135 the ``read(nbytes)`` method, returning the empty string when there's no more
136 data.
137
138
139.. method:: xmlparser.SetBase(base)
140
141 Sets the base to be used for resolving relative URIs in system identifiers in
142 declarations. Resolving relative identifiers is left to the application: this
143 value will be passed through as the *base* argument to the
144 :func:`ExternalEntityRefHandler`, :func:`NotationDeclHandler`, and
145 :func:`UnparsedEntityDeclHandler` functions.
146
147
148.. method:: xmlparser.GetBase()
149
150 Returns a string containing the base set by a previous call to :meth:`SetBase`,
151 or ``None`` if :meth:`SetBase` hasn't been called.
152
153
154.. method:: xmlparser.GetInputContext()
155
156 Returns the input data that generated the current event as a string. The data is
157 in the encoding of the entity which contains the text. When called while an
158 event handler is not active, the return value is ``None``.
159
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161.. method:: xmlparser.ExternalEntityParserCreate(context[, encoding])
162
163 Create a "child" parser which can be used to parse an external parsed entity
164 referred to by content parsed by the parent parser. The *context* parameter
165 should be the string passed to the :meth:`ExternalEntityRefHandler` handler
166 function, described below. The child parser is created with the
167 :attr:`ordered_attributes` and :attr:`specified_attributes` set to the values of
168 this parser.
169
Antoine Pitroua83878e2011-01-05 18:37:22 +0000170.. method:: xmlparser.SetParamEntityParsing(flag)
171
172 Control parsing of parameter entities (including the external DTD subset).
173 Possible *flag* values are :const:`XML_PARAM_ENTITY_PARSING_NEVER`,
174 :const:`XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE` and
175 :const:`XML_PARAM_ENTITY_PARSING_ALWAYS`. Return true if setting the flag
176 was successful.
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178.. method:: xmlparser.UseForeignDTD([flag])
179
180 Calling this with a true value for *flag* (the default) will cause Expat to call
181 the :attr:`ExternalEntityRefHandler` with :const:`None` for all arguments to
182 allow an alternate DTD to be loaded. If the document does not contain a
183 document type declaration, the :attr:`ExternalEntityRefHandler` will still be
184 called, but the :attr:`StartDoctypeDeclHandler` and
185 :attr:`EndDoctypeDeclHandler` will not be called.
186
187 Passing a false value for *flag* will cancel a previous call that passed a true
188 value, but otherwise has no effect.
189
190 This method can only be called before the :meth:`Parse` or :meth:`ParseFile`
191 methods are called; calling it after either of those have been called causes
192 :exc:`ExpatError` to be raised with the :attr:`code` attribute set to
Georg Brandlb4dac712010-10-15 14:46:48 +0000193 ``errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Georg Brandl116aa622007-08-15 14:28:22 +0000195:class:`xmlparser` objects have the following attributes:
196
197
198.. attribute:: xmlparser.buffer_size
199
Georg Brandl48310cd2009-01-03 21:18:54 +0000200 The size of the buffer used when :attr:`buffer_text` is true.
201 A new buffer size can be set by assigning a new integer value
202 to this attribute.
Christian Heimes2380ac72008-01-09 00:17:24 +0000203 When the size is changed, the buffer will be flushed.
204
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206.. attribute:: xmlparser.buffer_text
207
208 Setting this to true causes the :class:`xmlparser` object to buffer textual
209 content returned by Expat to avoid multiple calls to the
210 :meth:`CharacterDataHandler` callback whenever possible. This can improve
211 performance substantially since Expat normally breaks character data into chunks
212 at every line ending. This attribute is false by default, and may be changed at
213 any time.
214
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216.. attribute:: xmlparser.buffer_used
217
218 If :attr:`buffer_text` is enabled, the number of bytes stored in the buffer.
219 These bytes represent UTF-8 encoded text. This attribute has no meaningful
220 interpretation when :attr:`buffer_text` is false.
221
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223.. attribute:: xmlparser.ordered_attributes
224
225 Setting this attribute to a non-zero integer causes the attributes to be
226 reported as a list rather than a dictionary. The attributes are presented in
227 the order found in the document text. For each attribute, two list entries are
228 presented: the attribute name and the attribute value. (Older versions of this
229 module also used this format.) By default, this attribute is false; it may be
230 changed at any time.
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233.. attribute:: xmlparser.specified_attributes
234
235 If set to a non-zero integer, the parser will report only those attributes which
236 were specified in the document instance and not those which were derived from
237 attribute declarations. Applications which set this need to be especially
238 careful to use what additional information is available from the declarations as
239 needed to comply with the standards for the behavior of XML processors. By
240 default, this attribute is false; it may be changed at any time.
241
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243The following attributes contain values relating to the most recent error
244encountered by an :class:`xmlparser` object, and will only have correct values
245once a call to :meth:`Parse` or :meth:`ParseFile` has raised a
246:exc:`xml.parsers.expat.ExpatError` exception.
247
248
249.. attribute:: xmlparser.ErrorByteIndex
250
251 Byte index at which an error occurred.
252
253
254.. attribute:: xmlparser.ErrorCode
255
256 Numeric code specifying the problem. This value can be passed to the
257 :func:`ErrorString` function, or compared to one of the constants defined in the
258 ``errors`` object.
259
260
261.. attribute:: xmlparser.ErrorColumnNumber
262
263 Column number at which an error occurred.
264
265
266.. attribute:: xmlparser.ErrorLineNumber
267
268 Line number at which an error occurred.
269
270The following attributes contain values relating to the current parse location
271in an :class:`xmlparser` object. During a callback reporting a parse event they
272indicate the location of the first of the sequence of characters that generated
273the event. When called outside of a callback, the position indicated will be
274just past the last parse event (regardless of whether there was an associated
275callback).
276
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278.. attribute:: xmlparser.CurrentByteIndex
279
280 Current byte index in the parser input.
281
282
283.. attribute:: xmlparser.CurrentColumnNumber
284
285 Current column number in the parser input.
286
287
288.. attribute:: xmlparser.CurrentLineNumber
289
290 Current line number in the parser input.
291
292Here is the list of handlers that can be set. To set a handler on an
293:class:`xmlparser` object *o*, use ``o.handlername = func``. *handlername* must
294be taken from the following list, and *func* must be a callable object accepting
295the correct number of arguments. The arguments are all strings, unless
296otherwise stated.
297
298
299.. method:: xmlparser.XmlDeclHandler(version, encoding, standalone)
300
301 Called when the XML declaration is parsed. The XML declaration is the
302 (optional) declaration of the applicable version of the XML recommendation, the
303 encoding of the document text, and an optional "standalone" declaration.
304 *version* and *encoding* will be strings, and *standalone* will be ``1`` if the
305 document is declared standalone, ``0`` if it is declared not to be standalone,
306 or ``-1`` if the standalone clause was omitted. This is only available with
307 Expat version 1.95.0 or newer.
308
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310.. method:: xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset)
311
312 Called when Expat begins parsing the document type declaration (``<!DOCTYPE
313 ...``). The *doctypeName* is provided exactly as presented. The *systemId* and
314 *publicId* parameters give the system and public identifiers if specified, or
315 ``None`` if omitted. *has_internal_subset* will be true if the document
316 contains and internal document declaration subset. This requires Expat version
317 1.2 or newer.
318
319
320.. method:: xmlparser.EndDoctypeDeclHandler()
321
322 Called when Expat is done parsing the document type declaration. This requires
323 Expat version 1.2 or newer.
324
325
326.. method:: xmlparser.ElementDeclHandler(name, model)
327
328 Called once for each element type declaration. *name* is the name of the
329 element type, and *model* is a representation of the content model.
330
331
332.. method:: xmlparser.AttlistDeclHandler(elname, attname, type, default, required)
333
334 Called for each declared attribute for an element type. If an attribute list
335 declaration declares three attributes, this handler is called three times, once
336 for each attribute. *elname* is the name of the element to which the
337 declaration applies and *attname* is the name of the attribute declared. The
338 attribute type is a string passed as *type*; the possible values are
339 ``'CDATA'``, ``'ID'``, ``'IDREF'``, ... *default* gives the default value for
340 the attribute used when the attribute is not specified by the document instance,
341 or ``None`` if there is no default value (``#IMPLIED`` values). If the
342 attribute is required to be given in the document instance, *required* will be
343 true. This requires Expat version 1.95.0 or newer.
344
345
346.. method:: xmlparser.StartElementHandler(name, attributes)
347
348 Called for the start of every element. *name* is a string containing the
Eli Benderskyca4d97e2013-08-25 19:05:55 -0700349 element name, and *attributes* is the element attributes. If
350 :attr:`ordered_attributes` is true, this is a list (see
351 :attr:`ordered_attributes` for a full description). Otherwise it's a
352 dictionary mapping names to values.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354
355.. method:: xmlparser.EndElementHandler(name)
356
357 Called for the end of every element.
358
359
360.. method:: xmlparser.ProcessingInstructionHandler(target, data)
361
362 Called for every processing instruction.
363
364
365.. method:: xmlparser.CharacterDataHandler(data)
366
367 Called for character data. This will be called for normal character data, CDATA
368 marked content, and ignorable whitespace. Applications which must distinguish
369 these cases can use the :attr:`StartCdataSectionHandler`,
370 :attr:`EndCdataSectionHandler`, and :attr:`ElementDeclHandler` callbacks to
371 collect the required information.
372
373
374.. method:: xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName)
375
376 Called for unparsed (NDATA) entity declarations. This is only present for
377 version 1.2 of the Expat library; for more recent versions, use
378 :attr:`EntityDeclHandler` instead. (The underlying function in the Expat
379 library has been declared obsolete.)
380
381
382.. method:: xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)
383
384 Called for all entity declarations. For parameter and internal entities,
385 *value* will be a string giving the declared contents of the entity; this will
386 be ``None`` for external entities. The *notationName* parameter will be
387 ``None`` for parsed entities, and the name of the notation for unparsed
388 entities. *is_parameter_entity* will be true if the entity is a parameter entity
389 or false for general entities (most applications only need to be concerned with
390 general entities). This is only available starting with version 1.95.0 of the
391 Expat library.
392
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394.. method:: xmlparser.NotationDeclHandler(notationName, base, systemId, publicId)
395
396 Called for notation declarations. *notationName*, *base*, and *systemId*, and
397 *publicId* are strings if given. If the public identifier is omitted,
398 *publicId* will be ``None``.
399
400
401.. method:: xmlparser.StartNamespaceDeclHandler(prefix, uri)
402
403 Called when an element contains a namespace declaration. Namespace declarations
404 are processed before the :attr:`StartElementHandler` is called for the element
405 on which declarations are placed.
406
407
408.. method:: xmlparser.EndNamespaceDeclHandler(prefix)
409
410 Called when the closing tag is reached for an element that contained a
411 namespace declaration. This is called once for each namespace declaration on
412 the element in the reverse of the order for which the
413 :attr:`StartNamespaceDeclHandler` was called to indicate the start of each
414 namespace declaration's scope. Calls to this handler are made after the
415 corresponding :attr:`EndElementHandler` for the end of the element.
416
417
418.. method:: xmlparser.CommentHandler(data)
419
420 Called for comments. *data* is the text of the comment, excluding the leading
Ezio Melotti694f2332012-09-20 09:47:03 +0300421 ``'<!-``\ ``-'`` and trailing ``'-``\ ``->'``.
Georg Brandl116aa622007-08-15 14:28:22 +0000422
423
424.. method:: xmlparser.StartCdataSectionHandler()
425
426 Called at the start of a CDATA section. This and :attr:`EndCdataSectionHandler`
427 are needed to be able to identify the syntactical start and end for CDATA
428 sections.
429
430
431.. method:: xmlparser.EndCdataSectionHandler()
432
433 Called at the end of a CDATA section.
434
435
436.. method:: xmlparser.DefaultHandler(data)
437
438 Called for any characters in the XML document for which no applicable handler
439 has been specified. This means characters that are part of a construct which
440 could be reported, but for which no handler has been supplied.
441
442
443.. method:: xmlparser.DefaultHandlerExpand(data)
444
445 This is the same as the :func:`DefaultHandler`, but doesn't inhibit expansion
446 of internal entities. The entity reference will not be passed to the default
447 handler.
448
449
450.. method:: xmlparser.NotStandaloneHandler()
451
452 Called if the XML document hasn't been declared as being a standalone document.
453 This happens when there is an external subset or a reference to a parameter
454 entity, but the XML declaration does not set standalone to ``yes`` in an XML
Georg Brandl7cb13192010-08-03 12:06:29 +0000455 declaration. If this handler returns ``0``, then the parser will raise an
Georg Brandl116aa622007-08-15 14:28:22 +0000456 :const:`XML_ERROR_NOT_STANDALONE` error. If this handler is not set, no
457 exception is raised by the parser for this condition.
458
459
460.. method:: xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId)
461
462 Called for references to external entities. *base* is the current base, as set
463 by a previous call to :meth:`SetBase`. The public and system identifiers,
464 *systemId* and *publicId*, are strings if given; if the public identifier is not
465 given, *publicId* will be ``None``. The *context* value is opaque and should
466 only be used as described below.
467
468 For external entities to be parsed, this handler must be implemented. It is
469 responsible for creating the sub-parser using
470 ``ExternalEntityParserCreate(context)``, initializing it with the appropriate
471 callbacks, and parsing the entity. This handler should return an integer; if it
Georg Brandl7cb13192010-08-03 12:06:29 +0000472 returns ``0``, the parser will raise an
Georg Brandl116aa622007-08-15 14:28:22 +0000473 :const:`XML_ERROR_EXTERNAL_ENTITY_HANDLING` error, otherwise parsing will
474 continue.
475
476 If this handler is not provided, external entities are reported by the
477 :attr:`DefaultHandler` callback, if provided.
478
479
480.. _expaterror-objects:
481
482ExpatError Exceptions
483---------------------
484
485.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
486
487
488:exc:`ExpatError` exceptions have a number of interesting attributes:
489
490
491.. attribute:: ExpatError.code
492
Georg Brandlb4dac712010-10-15 14:46:48 +0000493 Expat's internal error number for the specific error. The
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300494 :data:`errors.messages <xml.parsers.expat.errors.messages>` dictionary maps
495 these error numbers to Expat's error messages. For example::
Georg Brandlb4dac712010-10-15 14:46:48 +0000496
497 from xml.parsers.expat import ParserCreate, ExpatError, errors
498
499 p = ParserCreate()
500 try:
501 p.Parse(some_xml_document)
502 except ExpatError as err:
503 print("Error:", errors.messages[err.code])
504
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300505 The :mod:`~xml.parsers.expat.errors` module also provides error message
506 constants and a dictionary :data:`~xml.parsers.expat.errors.codes` mapping
507 these messages back to the error codes, see below.
Georg Brandl116aa622007-08-15 14:28:22 +0000508
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510.. attribute:: ExpatError.lineno
511
512 Line number on which the error was detected. The first line is numbered ``1``.
513
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515.. attribute:: ExpatError.offset
516
517 Character offset into the line where the error occurred. The first column is
518 numbered ``0``.
519
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521.. _expat-example:
522
523Example
524-------
525
526The following program defines three handlers that just print out their
527arguments. ::
528
529 import xml.parsers.expat
530
531 # 3 handler functions
532 def start_element(name, attrs):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000533 print('Start element:', name, attrs)
Georg Brandl116aa622007-08-15 14:28:22 +0000534 def end_element(name):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000535 print('End element:', name)
Georg Brandl116aa622007-08-15 14:28:22 +0000536 def char_data(data):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000537 print('Character data:', repr(data))
Georg Brandl116aa622007-08-15 14:28:22 +0000538
539 p = xml.parsers.expat.ParserCreate()
540
541 p.StartElementHandler = start_element
542 p.EndElementHandler = end_element
543 p.CharacterDataHandler = char_data
544
545 p.Parse("""<?xml version="1.0"?>
546 <parent id="top"><child1 name="paul">Text goes here</child1>
547 <child2 name="fred">More text</child2>
548 </parent>""", 1)
549
550The output from this program is::
551
552 Start element: parent {'id': 'top'}
553 Start element: child1 {'name': 'paul'}
554 Character data: 'Text goes here'
555 End element: child1
556 Character data: '\n'
557 Start element: child2 {'name': 'fred'}
558 Character data: 'More text'
559 End element: child2
560 Character data: '\n'
561 End element: parent
562
563
564.. _expat-content-models:
565
566Content Model Descriptions
567--------------------------
568
Georg Brandlb4dac712010-10-15 14:46:48 +0000569.. module:: xml.parsers.expat.model
Georg Brandl116aa622007-08-15 14:28:22 +0000570
Georg Brandlb4dac712010-10-15 14:46:48 +0000571.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
Georg Brandl116aa622007-08-15 14:28:22 +0000572
573Content modules are described using nested tuples. Each tuple contains four
574values: the type, the quantifier, the name, and a tuple of children. Children
575are simply additional content module descriptions.
576
Georg Brandlb4dac712010-10-15 14:46:48 +0000577The values of the first two fields are constants defined in the
578:mod:`xml.parsers.expat.model` module. These constants can be collected in two
Georg Brandl116aa622007-08-15 14:28:22 +0000579groups: the model type group and the quantifier group.
580
581The constants in the model type group are:
582
583
584.. data:: XML_CTYPE_ANY
585 :noindex:
586
587 The element named by the model name was declared to have a content model of
588 ``ANY``.
589
590
591.. data:: XML_CTYPE_CHOICE
592 :noindex:
593
594 The named element allows a choice from a number of options; this is used for
595 content models such as ``(A | B | C)``.
596
597
598.. data:: XML_CTYPE_EMPTY
599 :noindex:
600
601 Elements which are declared to be ``EMPTY`` have this model type.
602
603
604.. data:: XML_CTYPE_MIXED
605 :noindex:
606
607
608.. data:: XML_CTYPE_NAME
609 :noindex:
610
611
612.. data:: XML_CTYPE_SEQ
613 :noindex:
614
615 Models which represent a series of models which follow one after the other are
616 indicated with this model type. This is used for models such as ``(A, B, C)``.
617
618The constants in the quantifier group are:
619
620
621.. data:: XML_CQUANT_NONE
622 :noindex:
623
624 No modifier is given, so it can appear exactly once, as for ``A``.
625
626
627.. data:: XML_CQUANT_OPT
628 :noindex:
629
630 The model is optional: it can appear once or not at all, as for ``A?``.
631
632
633.. data:: XML_CQUANT_PLUS
634 :noindex:
635
636 The model must occur one or more times (like ``A+``).
637
638
639.. data:: XML_CQUANT_REP
640 :noindex:
641
642 The model must occur zero or more times, as for ``A*``.
643
644
645.. _expat-errors:
646
647Expat error constants
648---------------------
649
Georg Brandlb4dac712010-10-15 14:46:48 +0000650.. module:: xml.parsers.expat.errors
Georg Brandl116aa622007-08-15 14:28:22 +0000651
Georg Brandlb4dac712010-10-15 14:46:48 +0000652The following constants are provided in the :mod:`xml.parsers.expat.errors`
653module. These constants are useful in interpreting some of the attributes of
654the :exc:`ExpatError` exception objects raised when an error has occurred.
655Since for backwards compatibility reasons, the constants' value is the error
656*message* and not the numeric error *code*, you do this by comparing its
657:attr:`code` attribute with
658:samp:`errors.codes[errors.XML_ERROR_{CONSTANT_NAME}]`.
659
660The ``errors`` module has the following attributes:
661
662.. data:: codes
663
664 A dictionary mapping numeric error codes to their string descriptions.
665
666 .. versionadded:: 3.2
667
668
669.. data:: messages
670
671 A dictionary mapping string descriptions to their error codes.
672
673 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000674
675
676.. data:: XML_ERROR_ASYNC_ENTITY
Georg Brandl116aa622007-08-15 14:28:22 +0000677
678
679.. data:: XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000680
681 An entity reference in an attribute value referred to an external entity instead
682 of an internal entity.
683
684
685.. data:: XML_ERROR_BAD_CHAR_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000686
687 A character reference referred to a character which is illegal in XML (for
688 example, character ``0``, or '``&#0;``').
689
690
691.. data:: XML_ERROR_BINARY_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000692
693 An entity reference referred to an entity which was declared with a notation, so
694 cannot be parsed.
695
696
697.. data:: XML_ERROR_DUPLICATE_ATTRIBUTE
Georg Brandl116aa622007-08-15 14:28:22 +0000698
699 An attribute was used more than once in a start tag.
700
701
702.. data:: XML_ERROR_INCORRECT_ENCODING
Georg Brandl116aa622007-08-15 14:28:22 +0000703
704
705.. data:: XML_ERROR_INVALID_TOKEN
Georg Brandl116aa622007-08-15 14:28:22 +0000706
707 Raised when an input byte could not properly be assigned to a character; for
708 example, a NUL byte (value ``0``) in a UTF-8 input stream.
709
710
711.. data:: XML_ERROR_JUNK_AFTER_DOC_ELEMENT
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713 Something other than whitespace occurred after the document element.
714
715
716.. data:: XML_ERROR_MISPLACED_XML_PI
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718 An XML declaration was found somewhere other than the start of the input data.
719
720
721.. data:: XML_ERROR_NO_ELEMENTS
Georg Brandl116aa622007-08-15 14:28:22 +0000722
723 The document contains no elements (XML requires all documents to contain exactly
724 one top-level element)..
725
726
727.. data:: XML_ERROR_NO_MEMORY
Georg Brandl116aa622007-08-15 14:28:22 +0000728
729 Expat was not able to allocate memory internally.
730
731
732.. data:: XML_ERROR_PARAM_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000733
734 A parameter entity reference was found where it was not allowed.
735
736
737.. data:: XML_ERROR_PARTIAL_CHAR
Georg Brandl116aa622007-08-15 14:28:22 +0000738
739 An incomplete character was found in the input.
740
741
742.. data:: XML_ERROR_RECURSIVE_ENTITY_REF
Georg Brandl116aa622007-08-15 14:28:22 +0000743
744 An entity reference contained another reference to the same entity; possibly via
745 a different name, and possibly indirectly.
746
747
748.. data:: XML_ERROR_SYNTAX
Georg Brandl116aa622007-08-15 14:28:22 +0000749
750 Some unspecified syntax error was encountered.
751
752
753.. data:: XML_ERROR_TAG_MISMATCH
Georg Brandl116aa622007-08-15 14:28:22 +0000754
755 An end tag did not match the innermost open start tag.
756
757
758.. data:: XML_ERROR_UNCLOSED_TOKEN
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760 Some token (such as a start tag) was not closed before the end of the stream or
761 the next token was encountered.
762
763
764.. data:: XML_ERROR_UNDEFINED_ENTITY
Georg Brandl116aa622007-08-15 14:28:22 +0000765
Martin Panter7462b6492015-11-02 03:37:02 +0000766 A reference was made to an entity which was not defined.
Georg Brandl116aa622007-08-15 14:28:22 +0000767
768
769.. data:: XML_ERROR_UNKNOWN_ENCODING
Georg Brandl116aa622007-08-15 14:28:22 +0000770
771 The document encoding is not supported by Expat.
772
773
774.. data:: XML_ERROR_UNCLOSED_CDATA_SECTION
Georg Brandl116aa622007-08-15 14:28:22 +0000775
776 A CDATA marked section was not closed.
777
778
779.. data:: XML_ERROR_EXTERNAL_ENTITY_HANDLING
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781
782.. data:: XML_ERROR_NOT_STANDALONE
Georg Brandl116aa622007-08-15 14:28:22 +0000783
784 The parser determined that the document was not "standalone" though it declared
785 itself to be in the XML declaration, and the :attr:`NotStandaloneHandler` was
786 set and returned ``0``.
787
788
789.. data:: XML_ERROR_UNEXPECTED_STATE
Georg Brandl116aa622007-08-15 14:28:22 +0000790
791
792.. data:: XML_ERROR_ENTITY_DECLARED_IN_PE
Georg Brandl116aa622007-08-15 14:28:22 +0000793
794
795.. data:: XML_ERROR_FEATURE_REQUIRES_XML_DTD
Georg Brandl116aa622007-08-15 14:28:22 +0000796
797 An operation was requested that requires DTD support to be compiled in, but
798 Expat was configured without DTD support. This should never be reported by a
799 standard build of the :mod:`xml.parsers.expat` module.
800
801
802.. data:: XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING
Georg Brandl116aa622007-08-15 14:28:22 +0000803
804 A behavioral change was requested after parsing started that can only be changed
805 before parsing has started. This is (currently) only raised by
806 :meth:`UseForeignDTD`.
807
808
809.. data:: XML_ERROR_UNBOUND_PREFIX
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811 An undeclared prefix was found when namespace processing was enabled.
812
813
814.. data:: XML_ERROR_UNDECLARING_PREFIX
Georg Brandl116aa622007-08-15 14:28:22 +0000815
816 The document attempted to remove the namespace declaration associated with a
817 prefix.
818
819
820.. data:: XML_ERROR_INCOMPLETE_PE
Georg Brandl116aa622007-08-15 14:28:22 +0000821
822 A parameter entity contained incomplete markup.
823
824
825.. data:: XML_ERROR_XML_DECL
Georg Brandl116aa622007-08-15 14:28:22 +0000826
827 The document contained no document element at all.
828
829
830.. data:: XML_ERROR_TEXT_DECL
Georg Brandl116aa622007-08-15 14:28:22 +0000831
832 There was an error parsing a text declaration in an external entity.
833
834
835.. data:: XML_ERROR_PUBLICID
Georg Brandl116aa622007-08-15 14:28:22 +0000836
837 Characters were found in the public id that are not allowed.
838
839
840.. data:: XML_ERROR_SUSPENDED
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842 The requested operation was made on a suspended parser, but isn't allowed. This
843 includes attempts to provide additional input or to stop the parser.
844
845
846.. data:: XML_ERROR_NOT_SUSPENDED
Georg Brandl116aa622007-08-15 14:28:22 +0000847
848 An attempt to resume the parser was made when the parser had not been suspended.
849
850
851.. data:: XML_ERROR_ABORTED
Georg Brandl116aa622007-08-15 14:28:22 +0000852
853 This should not be reported to Python applications.
854
855
856.. data:: XML_ERROR_FINISHED
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858 The requested operation was made on a parser which was finished parsing input,
859 but isn't allowed. This includes attempts to provide additional input or to
860 stop the parser.
861
862
863.. data:: XML_ERROR_SUSPEND_PE
Georg Brandl116aa622007-08-15 14:28:22 +0000864
Christian Heimesb186d002008-03-18 15:15:01 +0000865
866.. rubric:: Footnotes
867
868.. [#] The encoding string included in XML output should conform to the
869 appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
870 not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
Georg Brandlb7354a62014-10-29 10:57:37 +0100871 and http://www.iana.org/assignments/character-sets/character-sets.xhtml.
Christian Heimesb186d002008-03-18 15:15:01 +0000872