xml.parsers.expat — Fast XML parsing using Expat¶
Примітка
If you need to parse untrusted or unauthenticated data, see XML security.
The xml.parsers.expat module is a Python interface to the Expat
non-validating XML parser. The module provides a single extension type,
xmlparser, that represents the current state of an XML parser. After
an xmlparser object has been created, various attributes of the object
can be set to handler functions. When an XML document is then fed to the
parser, the handler functions are called for the character data and markup in
the XML document.
Цей модуль використовує модуль pyexpat для надання доступу до аналізатора Expat. Пряме використання модуля pyexpat застаріло.
This module provides the following exception, type object and data items:
- exception xml.parsers.expat.ExpatError¶
Виняток виникає, коли Expat повідомляє про помилку. Перегляньте розділ Винятки ExpatError для отримання додаткової інформації про інтерпретацію помилок Expat.
- exception xml.parsers.expat.error¶
Псевдонім для
ExpatError.
- xml.parsers.expat.XMLParserType¶
Тип значень, які повертає функція
ParserCreate().
- xml.parsers.expat.EXPAT_VERSION¶
The version string of the Expat library loaded by the interpreter, like
'expat_2.8.4'.
- xml.parsers.expat.version_info¶
The version of the Expat library loaded by the interpreter, as a tuple of three integers: major, minor and micro version.
- xml.parsers.expat.features¶
The list of the features with which the loaded Expat library was compiled, as
(name, value)pairs. The value is only meaningful for features which have one, like'XML_CONTEXT_BYTES'or the default protection limits'XML_BLAP_ACT_THRES'and'XML_AT_MAX_AMP'; for other features, like'XML_DTD'and'XML_NS', the value is0and only the presence of the name is significant.
The xml.parsers.expat module contains two functions:
- xml.parsers.expat.ErrorString(errno)¶
Повертає пояснювальний рядок для заданого номера помилки errno.
- xml.parsers.expat.ParserCreate(encoding=None, namespace_separator=None, intern=None)¶
Creates and returns a new
xmlparserobject. encoding [1], if specified, must be a string naming the encoding used by the XML data. If it is given it will override the implicit or explicit encoding of the document.Деталі реалізації CPython: Expat natively understands and processes UTF-8, UTF-16, UTF-16BE, UTF-16LE, ISO-8859-1, and US-ASCII. For other encodings (including aliases like Latin1 and ASCII) it falls back to Python. It supports most of 8-bit encodings and many multi-byte encodings like Shift_JIS, although only BMP characters (
U+0000-U+FFFF) are supported with non-native encodings (this restriction is also applied to aliases like UTF8). These restrictions only apply if encoding is not given.Змінено в версії 3.16.0a0 (unreleased): Added support for multi-byte encodings.
Parsers created through
ParserCreate()are called «root» parsers, in the sense that they do not have any parent parser attached. Non-root parsers are created byparser.ExternalEntityParserCreate.Експат може додатково виконувати обробку простору імен XML для вас, увімкнувши значення для namespace_separator. Значення має бути односимвольним рядком; a
ValueErrorбуде викликано, якщо рядок має недопустиму довжину (Noneвважається тим самим, що пропуск). Коли обробку простору імен увімкнено, назви типів елементів і назви атрибутів, які належать до простору імен, будуть розгорнуті. Ім’я елемента, яке передається обробникам елементаStartElementHandlerіEndElementHandler, буде конкатенацією URI простору імен, символу роздільника простору імен і локальної частини імені. Якщо роздільником простору імен є нульовий байт (chr(0)), тоді URI простору імен і локальна частина будуть об’єднані без будь-якого роздільника.Наприклад, якщо namespace_separator встановлено на символ пробілу (
' '), а наступний документ аналізується:<?xml version="1.0"?> <root xmlns = "http://default-namespace.org/" xmlns:py = "http://www.python.org/ns/"> <py:elem1 /> <elem2 xmlns="" /> </root>
StartElementHandlerотримає такі рядки для кожного елемента:http://default-namespace.org/ root http://www.python.org/ns/ elem1 elem2
intern, if given, must be a dictionary. It is used to intern the names of elements and attributes, and is available as the
internattribute. By default a new empty dictionary is created for every parser.Через обмеження бібліотеки
Expat, яку використовуєpyexpat, повернутий екземплярxmlparserможна використовувати лише для аналізу одного документа XML. ВикликайтеParserCreateдля кожного документа, щоб надати унікальні екземпляри аналізатора.
Дивись також
- Аналізатор Expat XML
Домашня сторінка проекту Expat.
Об’єкти XMLParser¶
Об’єкти xmlparser мають такі методи:
- xmlparser.Parse(data[, isfinal])¶
Parses the contents of data, calling the appropriate handler functions to process the parsed data. data can be a bytes-like object or a string. If it is a string, the encoding declaration in the XML data is ignored, and the data is parsed as already decoded text. isfinal must be true on the final call to this method; it allows the parsing of a single file in fragments, not the submission of multiple files. data can be empty at any time.
- xmlparser.ParseFile(file)¶
Parse XML data reading from the object file. file only needs to provide the
read(nbytes)method, which returns bytes, and an empty bytes object when there’s no more data. Text files are not supported; useParse()for data which is already decoded.
- xmlparser.SetBase(base)¶
Встановлює базу для визначення відносних URI у системних ідентифікаторах у оголошеннях. Розпізнавання відносних ідентифікаторів залишається за додатком: це значення буде передано як аргумент base до функцій
ExternalEntityRefHandler(),NotationDeclHandler()іUnparsedEntityDeclHandler().
- xmlparser.GetBase()¶
Повертає рядок, що містить базовий набір попереднім викликом
SetBase()абоNone, якщоSetBase()не викликався.
- xmlparser.GetSpecifiedAttributeCount()¶
Return the index just past the attributes given in the start tag. Attributes defaulted from the DTD follow the specified ones, so attributes at lower indices in the list passed to
StartElementHandlerwere given in the start tag. Each attribute takes two items in that list, its name and its value. Only meaningful inside aStartElementHandlercall, and only ifordered_attributesis true.Added in version 3.16.0a0 (unreleased).
- xmlparser.GetInputContext()¶
Returns the input data which generated the current event as a
bytesobject. The data is in the encoding of the entity which contains the text. It extends to the end of the currently buffered input, therefore it can contain also the data of the following events, and if the event was generated by a large amount of text, not all of it may be available. When called while an event handler is not active, the return value isNone.
- xmlparser.ExternalEntityParserCreate(context[, encoding])¶
Створіть «дочірній» аналізатор, який можна використовувати для аналізу зовнішньої проаналізованої сутності, на яку посилається вміст, розібраний батьківським аналізатором. Параметр context має бути рядком, який передається до функції обробки
ExternalEntityRefHandler(), описаної нижче. Дочірній аналізатор створюється зordered_attributesіspecified_attributes, встановленими на значення цього аналізатора.
- xmlparser.SetParamEntityParsing(flag)¶
Контроль аналізу сутностей параметрів (включаючи підмножину зовнішнього DTD). Можливі значення flag:
XML_PARAM_ENTITY_PARSING_NEVER,XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONEіXML_PARAM_ENTITY_PARSING_ALWAYS. Повертає true, якщо прапорець встановлено успішно.
- xmlparser.UseForeignDTD([flag])¶
Виклик цього з істинним значенням для flag (за замовчуванням) змусить Expat викликати
ExternalEntityRefHandlerзNoneдля всіх аргументів, щоб дозволити завантажувати альтернативний DTD. Якщо документ не містить оголошення типу документа,ExternalEntityRefHandlerвсе одно буде викликано, алеStartDoctypeDeclHandlerіEndDoctypeDeclHandlerне буде викликано.Передача хибного значення для flag призведе до скасування попереднього виклику, який передав істинне значення, але в іншому випадку не матиме ефекту.
Цей метод можна викликати лише перед викликом методів
Parse()абоParseFile(); його виклик після виклику будь-якого з них викликаєExpatError, коли атрибутcodeмає значенняerrors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING].
- xmlparser.SetReparseDeferralEnabled(enabled)¶
Попередження
Calling
SetReparseDeferralEnabled(False)has security implications, as detailed below; please make sure to understand these consequences prior to using theSetReparseDeferralEnabledmethod.Expat 2.6.0 introduced a security mechanism called «reparse deferral» where instead of causing denial of service through quadratic runtime from reparsing large tokens, reparsing of unfinished tokens is now delayed by default until a sufficient amount of input is reached. Due to this delay, registered handlers may — depending of the sizing of input chunks pushed to Expat — no longer be called right after pushing new input to the parser. Where immediate feedback and taking over responsibility of protecting against denial of service from large tokens are both wanted, calling
SetReparseDeferralEnabled(False)disables reparse deferral for the current Expat parser instance, temporarily or altogether. CallingSetReparseDeferralEnabled(True)allows re-enabling reparse deferral.SetReparseDeferralEnabled()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.Added in version 3.13.
- xmlparser.GetReparseDeferralEnabled()¶
Returns whether reparse deferral is currently enabled for the given Expat parser instance.
Added in version 3.13.
xmlparser objects have the following methods to tune protections
against some common XML vulnerabilities.
- xmlparser.SetBillionLaughsAttackProtectionActivationThreshold(threshold, /)¶
Sets the number of output bytes needed to activate protection against billion laughs attacks.
The number of output bytes includes amplification from entity expansion and reading DTD files.
Parser objects usually have a protection activation threshold of 8 MiB, but the actual default value depends on the underlying Expat library.
An
ExpatErroris raised if this method is called on a non-root parser. The correspondinglinenoandoffsetshould not be used as they may have no special meaning.SetBillionLaughsAttackProtectionActivationThreshold()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.Примітка
Activation thresholds below 4 MiB are known to break support for DITA 1.3 payload and are hence not recommended.
Added in version 3.15.
- xmlparser.SetBillionLaughsAttackProtectionMaximumAmplification(max_factor, /)¶
Sets the maximum tolerated amplification factor for protection against billion laughs attacks.
The amplification factor is calculated as
(direct + indirect) / directwhile parsing, wheredirectis the number of bytes read from the primary document in parsing andindirectis the number of bytes added by expanding entities and reading of external DTD files.The max_factor value must be a non-NaN
floatvalue greater than or equal to 1.0. Peak amplifications of factor 15,000 for the entire payload and of factor 30,000 in the middle of parsing have been observed with small benign files in practice. In particular, the activation threshold should be carefully chosen to avoid false positives.Parser objects usually have a maximum amplification factor of 100, but the actual default value depends on the underlying Expat library.
An
ExpatErroris raised if this method is called on a non-root parser or if max_factor is outside the valid range. The correspondinglinenoandoffsetshould not be used as they may have no special meaning.SetBillionLaughsAttackProtectionMaximumAmplification()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.Примітка
The maximum amplification factor is only considered if the threshold that can be adjusted by
SetBillionLaughsAttackProtectionActivationThreshold()is exceeded.Added in version 3.15.
- xmlparser.SetAllocTrackerActivationThreshold(threshold, /)¶
Sets the number of allocated bytes of dynamic memory needed to activate protection against disproportionate use of RAM.
Parser objects usually have an allocation activation threshold of 64 MiB, but the actual default value depends on the underlying Expat library.
An
ExpatErroris raised if this method is called on a non-root parser. The correspondinglinenoandoffsetshould not be used as they may have no special meaning.SetAllocTrackerActivationThreshold()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.Added in version 3.15.
- xmlparser.SetAllocTrackerMaximumAmplification(max_factor, /)¶
Sets the maximum amplification factor between direct input and bytes of dynamic memory allocated.
The amplification factor is calculated as
allocated / directwhile parsing, wheredirectis the number of bytes read from the primary document in parsing andallocatedis the number of bytes of dynamic memory allocated in the parser hierarchy.The max_factor value must be a non-NaN
floatvalue greater than or equal to 1.0. Amplification factors greater than 100.0 can be observed near the start of parsing even with benign files in practice. In particular, the activation threshold should be carefully chosen to avoid false positives.Parser objects usually have a maximum amplification factor of 100, but the actual default value depends on the underlying Expat library.
An
ExpatErroris raised if this method is called on a non-root parser or if max_factor is outside the valid range. The correspondinglinenoandoffsetshould not be used as they may have no special meaning.SetAllocTrackerMaximumAmplification()has been backported to some prior releases of CPython as a security fix. Check for availability usinghasattr()if used in code running across a variety of Python versions.Примітка
The maximum amplification factor is only considered if the threshold that can be adjusted by
SetAllocTrackerActivationThreshold()is exceeded.Added in version 3.15.
Об’єкти xmlparser мають такі атрибути:
- xmlparser.buffer_size¶
Розмір буфера, який використовується, коли
buffer_textмає значення true. Новий розмір буфера можна встановити, присвоївши цьому атрибуту нове ціле значення. Коли розмір змінено, буфер буде очищено.
- xmlparser.buffer_text¶
Setting this to true causes the
xmlparserobject to buffer textual content returned by Expat to avoid multiple calls to theCharacterDataHandler()callback whenever possible. This can improve performance substantially since Expat normally breaks character data into chunks at every line ending. This attribute is false by default, and may be changed at any time. Note that when it is false, data that does not contain newlines may be chunked too.
- xmlparser.buffer_used¶
Якщо
buffer_textувімкнено, кількість байтів, що зберігаються в буфері. Ці байти представляють текст у кодуванні UTF-8. Цей атрибут не має значущої інтерпретації, якщоbuffer_textмає значення false.
- xmlparser.ordered_attributes¶
Встановлення для цього атрибута ненульового цілого числа призводить до того, що атрибути повідомлятимуться як список, а не як словник. Атрибути представлені в порядку, указаному в тексті документа. Для кожного атрибута представлено два записи списку: назва атрибута та значення атрибута. (Старіші версії цього модуля також використовували цей формат.) За замовчуванням цей атрибут має значення false; його можна змінити в будь-який час.
- xmlparser.specified_attributes¶
Якщо встановлено ненульове ціле число, аналізатор повідомлятиме лише про ті атрибути, які були вказані в екземплярі документа, а не про ті, які були отримані з оголошень атрибутів. Програми, які встановлюють це, повинні бути особливо обережними, щоб використовувати додаткову інформацію, доступну з декларацій, якщо це необхідно для відповідності стандартам поведінки процесорів XML. За замовчуванням цей атрибут має значення false; його можна змінити в будь-який час.
- xmlparser.intern¶
The dictionary used to intern the names of elements and attributes. It is either the dictionary passed as the intern argument of
ParserCreate(), or a new dictionary created for this parser.
- xmlparser.namespace_prefixes¶
If set to a true value, and namespace processing is enabled, the namespace prefix is reported as the third part of the expanded name, separated by the namespace separator. Names which have no prefix are not affected. By default, this attribute is false; it may be changed at any time.
Наступні атрибути містять значення, пов’язані з останньою помилкою, яку виявив об’єкт xmlparser, і матимуть правильні значення лише тоді, коли виклик Parse() або ParseFile() викликає Виняток xml.parsers.expat.ExpatError.
- xmlparser.ErrorByteIndex¶
Індекс байта, на якому сталася помилка.
- xmlparser.ErrorCode¶
Числовий код, що визначає проблему. Це значення можна передати у функцію
ErrorString()або порівняти з однією з констант, визначених в об’єктіerrors.
- xmlparser.ErrorColumnNumber¶
Номер стовпця, в якому сталася помилка.
- xmlparser.ErrorLineNumber¶
Номер рядка, в якому сталася помилка.
Наступні атрибути містять значення, пов’язані з поточним місцем аналізу в об’єкті xmlparser. Під час зворотного виклику, повідомляючи про подію синтаксичного аналізу, вони вказують розташування першого з послідовності символів, які породили подію. При виклику за межами зворотного виклику вказана позиція буде відразу після останньої події аналізу (незалежно від того, чи був пов’язаний зворотний виклик).
- xmlparser.CurrentByteIndex¶
Поточний індекс байта у вхідних даних аналізатора.
- xmlparser.CurrentColumnNumber¶
Поточний номер стовпця у вхідних даних аналізатора.
- xmlparser.CurrentLineNumber¶
Поточний номер рядка у вхідних даних аналізатора.
Ось список обробників, які можна встановити. Щоб встановити обробник для об’єкта xmlparser o, використовуйте o.handlername = func. handlername має бути взято з наступного списку, а func має бути викликаним об’єктом, який приймає правильну кількість аргументів. Усі аргументи є рядками, якщо не вказано інше.
- xmlparser.XmlDeclHandler(version, encoding, standalone)¶
Called when the XML declaration is parsed. The XML declaration is the (optional) declaration of the applicable version of the XML recommendation, the encoding of the document text, and an optional «standalone» declaration. version and encoding will be strings, and standalone will be
1if the document is declared standalone,0if it is declared not to be standalone, or-1if the standalone clause was omitted.
- xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset)¶
Called when Expat begins parsing the document type declaration (
<!DOCTYPE ...). The doctypeName is provided exactly as presented. The systemId and publicId parameters give the system and public identifiers if specified, orNoneif omitted. has_internal_subset will be true if the document contains an internal document declaration subset.
- xmlparser.EndDoctypeDeclHandler()¶
Called when Expat is done parsing the document type declaration.
- xmlparser.ElementDeclHandler(name, model)¶
Викликається один раз для кожного оголошення типу елемента. name — це ім’я типу елемента, а model — це представлення моделі вмісту.
- xmlparser.AttlistDeclHandler(elname, attname, type, default, required)¶
Called for each declared attribute for an element type. If an attribute list declaration declares three attributes, this handler is called three times, once for each attribute. elname is the name of the element to which the declaration applies and attname is the name of the attribute declared. The The attribute type is a string passed as type:
'CDATA','ID','IDREF','IDREFS','ENTITY','ENTITIES','NMTOKEN'or'NMTOKENS', an enumeration like'(x|y)', or a notation list like'NOTATION(n1|n2)'. default gives the default value for the attribute used when the attribute is not specified by the document instance, orNoneif there is no default value (#IMPLIEDvalues). If the attribute is required to be given in the document instance, required will be true.
- xmlparser.StartElementHandler(name, attributes)¶
Викликається для початку кожного елемента. name — це рядок, що містить назву елемента, а attributes — це атрибути елемента. Якщо
ordered_attributesмає значення true, це список (див.ordered_attributesдля повного опису). В іншому випадку це словник, який зіставляє імена зі значеннями.
- xmlparser.EndElementHandler(name)¶
Викликається в кінці кожного елемента.
- xmlparser.ProcessingInstructionHandler(target, data)¶
Викликається для кожної інструкції з обробки.
- xmlparser.CharacterDataHandler(data)¶
Called for character data. This will be called for normal character data, CDATA marked content, and ignorable whitespace. Applications which must distinguish these cases can use the
StartCdataSectionHandler,EndCdataSectionHandler, andElementDeclHandlercallbacks to collect the required information. Note that the character data may be chunked even if it is short and so you may receive more than one call toCharacterDataHandler(). Set thebuffer_textinstance attribute toTrueto avoid that.
- xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName)¶
Called for unparsed (NDATA) entity declarations. If this handler is not set, such declarations are reported by
EntityDeclHandler, which is preferred for new code. (The underlying function in the Expat library has been declared obsolete.)
- xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)¶
Called for all entity declarations. For parameter and internal entities, value will be a string giving the declared contents of the entity; this will be
Nonefor external entities. The notationName parameter will beNonefor parsed entities, and the name of the notation for unparsed entities. is_parameter_entity will be true if the entity is a parameter entity or false for general entities (most applications only need to be concerned with general entities).
- xmlparser.NotationDeclHandler(notationName, base, systemId, publicId)¶
Викликані нотні декларації. notationName, base, systemId і publicId є рядками, якщо вони задані. Якщо публічний ідентифікатор пропущено, publicId матиме значення
None.
- xmlparser.StartNamespaceDeclHandler(prefix, uri)¶
Викликається, коли елемент містить оголошення простору імен. Оголошення простору імен обробляються перед викликом
StartElementHandlerдля елемента, на якому розміщено оголошення.
- xmlparser.EndNamespaceDeclHandler(prefix)¶
Викликається, коли досягається закриваючий тег для елемента, який містив оголошення простору імен. Це викликається один раз для кожної декларації простору імен для елемента в порядку, зворотному порядку, для якого було викликано
StartNamespaceDeclHandler, щоб вказати початок кожної області декларації простору імен. Виклики цього обробника здійснюються після відповідногоEndElementHandlerдля кінця елемента.
- xmlparser.CommentHandler(data)¶
Звертався за коментарями. data — це текст коментаря, за винятком початкового
'<!--'і кінцевого'-->'.
- xmlparser.StartCdataSectionHandler()¶
Викликається на початку розділу CDATA. Це та
EndCdataSectionHandlerпотрібні, щоб мати можливість ідентифікувати синтаксичний початок і кінець для розділів CDATA.
- xmlparser.EndCdataSectionHandler()¶
Викликається в кінці розділу CDATA.
- xmlparser.DefaultHandler(data)¶
Викликається для будь-яких символів у документі XML, для яких не вказано відповідний обробник. Це означає символи, які є частиною конструкції, про яку можна повідомити, але для яких не надано обробник.
- xmlparser.DefaultHandlerExpand(data)¶
This is the same as the
DefaultHandler, but doesn’t inhibit expansion of internal entities. The entity reference will not be passed to the default handler.
- xmlparser.NotStandaloneHandler()¶
Викликається, якщо документ XML не оголошено як окремий документ. Це трапляється, коли існує зовнішня підмножина або посилання на сутність параметра, але XML-декларація не встановлює standalone на
yesв XML-декларації. Якщо цей обробник повертає0, тоді аналізатор викличе помилкуXML_ERROR_NOT_STANDALONE. Якщо цей обробник не встановлено, синтаксичний аналізатор не створює винятків для цієї умови.
- xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId)¶
Попередження
Implementing a handler that accesses local files and/or the network may create a vulnerability to external entity attacks if
xmlparseris used with user-provided XML content. Please reflect on your threat model before implementing this handler.Викликаються посилання на зовнішні сутності. base — це поточна база, встановлена попереднім викликом
SetBase(). Загальнодоступні та системні ідентифікатори, systemId і publicId, є рядками, якщо вони задані; якщо публічний ідентифікатор не вказано, publicId будеNone. Значення context є непрозорим і його слід використовувати лише як описано нижче.Для аналізу зовнішніх об’єктів цей обробник має бути реалізований. Він відповідає за створення суб-парсера за допомогою
ExternalEntityParserCreate(context), його ініціалізацію за допомогою відповідних зворотних викликів і аналіз сутності. Цей обробник має повертати ціле число; якщо він повертає0, аналізатор викличе помилкуXML_ERROR_EXTERNAL_ENTITY_HANDLING, інакше аналіз продовжиться.Якщо цей обробник не надано, зовнішні сутності повідомляються зворотним викликом
DefaultHandler, якщо він надається.
- xmlparser.SkippedEntityHandler(entityName, is_parameter_entity)¶
Called for entity references which are not expanded, because the parser did not read the declaration of the entity. This happens when the external DTD subset or an external parameter entity is not parsed. is_parameter_entity is true for a parameter entity and false for a general entity.
Винятки ExpatError¶
Винятки ExpatError мають ряд цікавих атрибутів:
- ExpatError.code¶
Внутрішній номер помилки Expat для конкретної помилки. Словник
errors.messagesзіставляє ці номери помилок із повідомленнями про помилки Expat. Наприклад:from xml.parsers.expat import ParserCreate, ExpatError, errors p = ParserCreate() try: p.Parse(some_xml_document) except ExpatError as err: print("Error:", errors.messages[err.code])
Модуль
errorsтакож надає константи повідомлень про помилки та словникcodes, який відображає ці повідомлення назад до кодів помилок, див. нижче.
- ExpatError.lineno¶
Номер рядка, в якому виявлено помилку. Перший рядок має номер
1.
- ExpatError.offset¶
Зміщення символу в рядку, де сталася помилка. Перший стовпець має номер
0.
приклад¶
Наступна програма визначає три обробники, які просто виводять свої аргументи.
import xml.parsers.expat
# 3 handler functions
def start_element(name, attrs):
print('Start element:', name, attrs)
def end_element(name):
print('End element:', name)
def char_data(data):
print('Character data:', repr(data))
p = xml.parsers.expat.ParserCreate()
p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data
p.Parse("""<?xml version="1.0"?>
<parent id="top"><child1 name="paul">Text goes here</child1>
<child2 name="fred">More text</child2>
</parent>""", 1)
Результат цієї програми:
Start element: parent {'id': 'top'}
Start element: child1 {'name': 'paul'}
Character data: 'Text goes here'
End element: child1
Character data: '\n'
Start element: child2 {'name': 'fred'}
Character data: 'More text'
End element: child2
Character data: '\n'
End element: parent
Опис моделі вмісту¶
Моделі вмісту описуються за допомогою вкладених кортежів. Кожен кортеж містить чотири значення: тип, квантор, ім’я та кортеж дітей. Дочірні елементи – це просто додаткові описи моделі контенту.
The values of the first two fields are constants defined in the
xml.parsers.expat.model module. These constants can be collected in two
groups: the model type group and the quantifier group.
Константи в групі типу моделі:
- xml.parsers.expat.model.XML_CTYPE_ANY¶
Елемент, названий іменем моделі, було оголошено таким, що має модель вмісту «БУДЬ-ЯКА».
- xml.parsers.expat.model.XML_CTYPE_CHOICE¶
Названий елемент дозволяє вибирати з кількох варіантів; це використовується для моделей вмісту, таких як
(A | B | C).
- xml.parsers.expat.model.XML_CTYPE_EMPTY¶
Елементи, які оголошено як
EMPTY, мають цей тип моделі.
- xml.parsers.expat.model.XML_CTYPE_MIXED¶
The named element allows character data, optionally interspersed with the named children; this is used for content models such as
(#PCDATA)and(#PCDATA | A | B)*.
- xml.parsers.expat.model.XML_CTYPE_NAME¶
The model names a single element, as for
A.
- xml.parsers.expat.model.XML_CTYPE_SEQ¶
Моделі, які представляють серію моделей, що йдуть одна за одною, позначаються цим типом моделі. Це використовується для таких моделей, як «(A, B, C)».
Константи в групі кванторів такі:
- xml.parsers.expat.model.XML_CQUANT_NONE¶
Модифікатор не надано, тому він може з’явитися лише один раз, як для
A.
- xml.parsers.expat.model.XML_CQUANT_OPT¶
Модель необов’язкова: вона може з’являтися один раз або не з’являтися взагалі, як для
A?.
- xml.parsers.expat.model.XML_CQUANT_PLUS¶
Модель має зустрічатися один або кілька разів (наприклад,
A+).
- xml.parsers.expat.model.XML_CQUANT_REP¶
Модель має зустрічатися нуль або більше разів, як для
A*.
Константи помилок Expat¶
The following constants are provided in the xml.parsers.expat.errors
module. These constants are useful in interpreting some of the attributes of
the ExpatError exception objects raised when an error has occurred.
Since for backwards compatibility reasons, the constants“ value is the error
message and not the numeric error code, you do this by comparing its
code attribute with
errors.codes[errors.XML_ERROR_CONSTANT_NAME].
Модуль errors має такі атрибути:
- xml.parsers.expat.errors.codes¶
Словник, що зіставляє описи рядків із їхніми кодами помилок.
Added in version 3.2.
- xml.parsers.expat.errors.messages¶
Словник, що зіставляє числові коди помилок з їхніми описами рядків.
Added in version 3.2.
- xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY¶
- xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF¶
Посилання на сутність у значенні атрибута посилалося на зовнішню сутність замість внутрішньої сутності.
- xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF¶
Посилання на символ стосується символу, який є недопустимим у XML (наприклад, символ
0або „�“).
- xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF¶
Посилання на сутність посилається на сутність, яка була оголошена за допомогою нотації, тому не може бути проаналізована.
- xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE¶
Атрибут використовувався більше одного разу в початковому тегу.
- xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING¶
- xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN¶
Викликається, коли вхідний байт не може бути належним чином призначений символу; наприклад, байт NUL (значення
0) у вхідному потоці UTF-8.
- xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT¶
Щось інше, ніж пробіл, сталося після елемента документа.
- xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI¶
Оголошення XML знайдено не на початку вхідних даних.
- xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS¶
The document contains no elements (XML requires all documents to contain exactly one top-level element).
- xml.parsers.expat.errors.XML_ERROR_NO_MEMORY¶
Expat не зміг внутрішньо виділити пам’ять.
- xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF¶
Знайдено посилання на сутність параметра там, де це було заборонено.
- xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR¶
У вхідних даних знайдено неповний символ.
- xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF¶
Посилання на сутність містило інше посилання на ту саму сутність; можливо, через інше ім’я та, можливо, опосередковано.
- xml.parsers.expat.errors.XML_ERROR_SYNTAX¶
Виявлено невідому синтаксичну помилку.
- xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH¶
Кінцевий тег не збігається з внутрішнім відкритим початковим тегом.
- xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN¶
Деякий маркер (наприклад, початковий тег) не було закрито до кінця потоку або виявлено наступний маркер.
- xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY¶
Було зроблено посилання на сутність, яка не була визначена.
- xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING¶
Кодування документа не підтримується Expat.
- xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION¶
Розділ, позначений CDATA, не було закрито.
- xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING¶
- xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE¶
Синтаксичний аналізатор визначив, що документ не був «автономним», хоча він оголошував себе таким у декларації XML, а
NotStandaloneHandlerбуло встановлено та повернуто0.
- xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE¶
- xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE¶
- xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD¶
An operation was requested that requires DTD support to be compiled in, but Expat was configured without DTD support. This should never be reported by a standard build of the
xml.parsers.expatmodule.
- xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING¶
Після початку аналізу надійшов запит на зміну поведінки, яку можна змінити лише до початку аналізу. Це (наразі) викликає лише
UseForeignDTD().
- xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX¶
Коли обробку простору імен було ввімкнено, виявлено неоголошений префікс.
- xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX¶
У документі зроблено спробу видалити декларацію простору імен, пов’язану з префіксом.
- xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE¶
Сутність параметра містила неповну розмітку.
- xml.parsers.expat.errors.XML_ERROR_XML_DECL¶
There was an error parsing the XML declaration.
- xml.parsers.expat.errors.XML_ERROR_TEXT_DECL¶
Під час синтаксичного аналізу текстової декларації у зовнішній сутності сталася помилка.
- xml.parsers.expat.errors.XML_ERROR_PUBLICID¶
У загальнодоступному ідентифікаторі знайдено неприпустимі символи.
- xml.parsers.expat.errors.XML_ERROR_SUSPENDED¶
Потрібну операцію було виконано на призупиненому аналізаторі, але вона не дозволена. Це включає спроби надати додаткові вхідні дані або зупинити аналізатор.
- xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED¶
Спроба відновити аналізатор була зроблена, коли аналізатор не було призупинено.
- xml.parsers.expat.errors.XML_ERROR_ABORTED¶
Про це не слід повідомляти програми Python.
- xml.parsers.expat.errors.XML_ERROR_FINISHED¶
Потрібну операцію було виконано на синтаксичному аналізаторі, який завершив розбір вхідних даних, але це не дозволено. Це включає спроби надати додаткові вхідні дані або зупинити аналізатор.
- xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE¶
- xml.parsers.expat.errors.XML_ERROR_RESERVED_PREFIX_XML¶
An attempt was made to undeclare reserved namespace prefix
xmlor to bind it to another namespace URI.
- xml.parsers.expat.errors.XML_ERROR_RESERVED_PREFIX_XMLNS¶
An attempt was made to declare or undeclare reserved namespace prefix
xmlns.
- xml.parsers.expat.errors.XML_ERROR_RESERVED_NAMESPACE_URI¶
An attempt was made to bind the URI of one the reserved namespace prefixes
xmlandxmlnsto another namespace prefix.
- xml.parsers.expat.errors.XML_ERROR_INVALID_ARGUMENT¶
Про це не слід повідомляти програми Python.
- xml.parsers.expat.errors.XML_ERROR_NO_BUFFER¶
Про це не слід повідомляти програми Python.
- xml.parsers.expat.errors.XML_ERROR_AMPLIFICATION_LIMIT_BREACH¶
The limit on input amplification factor (from DTD and entities) has been breached.
- xml.parsers.expat.errors.XML_ERROR_NOT_STARTED¶
The parser was tried to be stopped or suspended before it started.
Added in version 3.14.
Виноски