xml.parsers.expat — Fast XML parsing using Expat — documentación de Python - 3.15.2
Navegación índice módulos | siguiente | anterior | Python » 3.15.2 documentation » The Python standard library » Herramientas Para Procesar Formatos de Marcado Estructurado » xml.parsers.expat — Fast XML parsing using Expat | Tema | xml.parsers.expat — Fast XML parsing using Expat ¶ Nota 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. Este módulo utiliza el módulo pyexpat para proporcionar acceso al analizador Expat.
El uso directo del módulo pyexpat está obsoleto. This module provides the following exception, type object and data items: exception xml.parsers.expat. ExpatError ¶ La excepción que se lanza cuando Expat informa un error. Consulte la sección Excepciones de ExpatError para obtener más información sobre cómo interpretar los errores de Expat. exception xml.parsers.expat. error ¶ Alias para ExpatError . xml.parsers.expat.
XMLParserType ¶ El tipo de los valores de retorno de la función 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 ) ¶ Retorna una cadena explicativa para un número de error dado errno . xml.parsers.expat.
ParserCreate ( encoding = None , namespace_separator = None , intern = None ) ¶ Crea y retorna un nuevo objeto xmlparser . encoding , si se especifica, debe ser una cadena que nombre la codificación utilizada por los datos XML. Expat no admite tantas codificaciones como Python, y su repertorio de codificaciones no se puede ampliar; es compatible con UTF-8, UTF-16, ISO-8859-1 (Latin1) y ASCII. Si se proporciona encoding [ 1 ] , anulará la codificación implícita o explícita del documento.
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 . Expat puede, opcionalmente, realizar el procesamiento del espacio de nombres XML por usted, habilitado al proporcionar un valor para namespace_separator . El valor debe ser una cadena de un carácter; a ValueError se lanzará si la cadena tiene una longitud ilegal ( None se considera lo mismo que una omisión).
Cuando el procesamiento de espacios de nombres está habilitado, se expandirán los nombres de tipos de elementos y los nombres de atributos que pertenecen a un espacio de nombres. El nombre del elemento pasado a los controladores de elementos StartElementHandler y EndElementHandler será la concatenación del URI del espacio de nombres, el carácter separador del espacio de nombres y la parte local del nombre. Si el separador del espacio de nombres es un byte cero ( chr(0) ), el URI del espacio de nombres y la parte local se concatenarán sin ningún separador.
Por ejemplo, si namespace_separator se establece en un carácter de espacio ( ' ' ) y se analiza el siguiente documento: <?xml version="1.0"?> <root xmlns = "http://default-namespace.org/" xmlns:py = "http://www.python.org/ns/" > <py:elem1 /> <elem2 xmlns= "" /> </root> StartElementHandler recibirá las siguientes cadenas para cada elemento: 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. Debido a las limitaciones en la biblioteca Expat utilizada por pyexpat , la instancia xmlparser retorna solo se puede usar para analizar un solo documento XML. Llame a ParserCreate para cada documento para proporcionar instancias de analizador únicas. Ver también El Expat XML Parser Página de inicio del proyecto Expat.
Objetos XMLParser ¶ Los objetos xmlparser tienen los siguientes métodos: 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 ) ¶ Establece la base que se utilizará para resolver URIs relativos en identificadores de sistema en declaraciones. La resolución de los identificadores relativos se deja en manos de la aplicación: este valor se pasará como el argumento base a las funciones ExternalEntityRefHandler() , NotationDeclHandler() , y UnparsedEntityDeclHandler() . xmlparser.
GetBase ( ) ¶ Retorna una cadena que contiene la base establecida por una llamada anterior a SetBase() , o None si no se ha llamado a 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 active, the return value is None . xmlparser. ExternalEntityParserCreate ( context [ , encoding ] ) ¶ Cree un analizador «child» que se pueda utilizar para analizar una entidad analizada externa a la que hace referencia el contenido analizado por el analizador principal. El parámetro context debe ser la cadena pasada a la función del controlador ExternalEntityRefHandler() , que se describe a continuación.
El analizador secundario se crea con order_attributes y specific_attributes establecidos en los valores de este analizador. xmlparser. SetParamEntityParsing ( flag ) ¶ Controle el análisis de las entidades de parámetros (incluido el subconjunto DTD externo). Los posibles valores de flag son XML_PARAM_ENTITY_PARSING_NEVER , XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE y XML_PARAM_ENTITY_PARSING_ALWAYS . Retorna verdadero si el establecimiento de la bandera fue exitoso. xmlparser.
UseForeignDTD ( [ flag ] ) ¶ Llamar a esto con un valor verdadero para flag (el predeterminado) hará que Expat llame a ExternalEntityRefHandler con None para todos los argumentos para permitir que se cargue una DTD alternativa. Si el documento no contiene una declaración de tipo de documento, se seguirá llamando a ExternalEntityRefHandler , pero no se llamará a StartDoctypeDeclHandler y EndDoctypeDeclHandler . Pasar un valor falso para flag cancelar�
The rest of this page is on the live site.