Text of docs.python.org › uk › 3 › library › pyexpat.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

xml.parsers.expat — Fast XML parsing using Expat — Python 3.15.2 documentation

Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Інструменти обробки структурованої розмітки » xml.parsers.expat — Fast XML parsing using Expat | Theme | 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 is 0 and 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 ) ¶ Створює та повертає новий об’єкт xmlparser . encoding , якщо вказано, має бути рядком із назвою кодування, що використовується в XML-даних. Expat не підтримує таку кількість кодувань, як Python, і його набір кодувань не можна розширити; він підтримує UTF-8, UTF-16, ISO-8859-1 (Latin1) і ASCII.

Якщо задано кодування [ 1 ] , воно замінить неявне або явне кодування документа. 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 by parser.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 intern attribute. 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; use Parse() for data which is already decoded. xmlparser. SetBase ( base ) ¶ Встановлює базу для визначення відносних URI у системних ідентифікаторах у оголошеннях. Розпізнавання відносних ідентифікаторів залишається за додатком: це значення буде передано як аргумент base до функцій ExternalEntityRefHandler() , NotationDeclHandler() і UnparsedEntityDeclHandler() . xmlparser.

GetBase ( ) ¶ Повертає рядок, що містить базовий набір попереднім викликом SetBase() або None , якщо SetBase() не викликався. xmlparser. GetInputContext ( ) ¶ Returns the input data which generated the current event as a bytes object. 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

The rest of this page is on the live site.