Python saxutils sax xml

xml.sax.saxutils — SAX утилиты¶

Модуль xml.sax.saxutils содержит ряд классов и функций, которые обычно используются при создании SAX приложений либо для непосредственного использования, либо в качестве базовых классов.

xml.sax.saxutils. escape ( data, entities=<> ) ¶

Экранирует ‘&’ , » в строке данных.

Вы можете экранировать другие строки данных, передав словарь в качестве необязательного параметра entities. Все ключи и значения должны быть строками; каждый ключ будет заменен соответствующим значением. Символы ‘&’ , » всегда экранируются, даже если указан entities.

xml.sax.saxutils. unescape ( data, entities=<> ) ¶

Отменяет экранирование ‘&’ , ‘<‘ и ‘>’ в строке данных.

Вы можете отменить экранирование других строк данных, передав словарь в качестве необязательного параметра entities. Все ключи и значения должны быть строками; каждый ключ будет заменен соответствующим значением. ‘&amp’ , ‘<‘ и ‘>’ всегда неэкранированы, даже если указан entities.

xml.sax.saxutils. quoteattr ( data, entities=<> ) ¶

Аналогична escape() , но также подготавливает data для использования в качестве значения атрибута. Возвращаемое значение представляет собой версию data в кавычках с любыми дополнительными необходимыми заменами. quoteattr() выберет символ кавычек на основе содержимого data, пытаясь избежать кодирования каких-либо символов кавычек в строке. Если символы одинарной и двойной кавычек уже находятся в data, символы двойных кавычек будут закодированы, а data будет заключён в двойные кавычки. Полученную строку можно использовать непосредственно как значение атрибута:

>>> print(«%s % quoteattr(«ab ‘ cd ef»))

Данная функция полезна при генерации значений атрибутов для HTML или любого SGML с использованием синтаксиса ссылок.

class xml.sax.saxutils. XMLGenerator ( out=None, encoding=’iso-8859-1′, short_empty_elements=False ) ¶

Класс реализует интерфейс ContentHandler , записывая SAX события обратно в XML-документ. Другими словами, использование XMLGenerator в качестве обработчика содержимого будет воспроизводить анализируемый исходный документ. out должен быть файлоподобным объектом, у которого по умолчанию значение sys.stdout. encoding — это кодировка выходного потока, которая по умолчанию имеет значение ‘iso-8859-1’ . short_empty_elements управляет форматированием элементов, не содержащих содержимого: если False (по умолчанию), они создаются как пара начальных/конечных тегов, если установлено значение True , они создаются как один самозакрывающийся тег.

Добавлено в версии 3.2: Параметр short_empty_elements.

Класс предназначен для размещения между XMLReader и обработчиками событий клиентского приложения. По умолчанию он ничего не делает, кроме как передает запросы считывателю и события обработчикам без изменений, но подклассы могут переопределять определённые методы для изменения потока событий или запросов конфигурации по мере их прохождения.

xml.sax.saxutils. prepare_input_source ( source, base=» ) ¶

Принимает источник ввода и необязательный базовый URL-адрес и возвращает полностью разрешенный объект InputSource , готовый для чтения. Источник ввода может быть указан в виде строки, файлового объекта или объекта InputSource ; парсеры будут использовать эту функцию для реализации полиморфного аргумента source в свой метод parse() .

Источник

xml.sax — Support for SAX2 parsers¶

The xml.sax package provides a number of modules which implement the Simple API for XML (SAX) interface for Python. The package itself provides the SAX exceptions and the convenience functions which will be most used by users of the SAX API.

The xml.sax module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities .

Changed in version 3.7.1: The SAX parser no longer processes general external entities by default to increase security. Before, the parser created network connections to fetch remote files or loaded local files from the file system for DTD and entities. The feature can be enabled again with method setFeature() on the parser object and argument feature_external_ges .

The convenience functions are:

xml.sax. make_parser ( parser_list = [] ) ¶

Create and return a SAX XMLReader object. The first parser found will be used. If parser_list is provided, it must be an iterable of strings which name modules that have a function named create_parser() . Modules listed in parser_list will be used before modules in the default list of parsers.

Changed in version 3.8: The parser_list argument can be any iterable, not just a list.

Create a SAX parser and use it to parse a document. The document, passed in as filename_or_stream, can be a filename or a file object. The handler parameter needs to be a SAX ContentHandler instance. If error_handler is given, it must be a SAX ErrorHandler instance; if omitted, SAXParseException will be raised on all errors. There is no return value; all work must be done by the handler passed in.

xml.sax. parseString ( string , handler , error_handler = handler.ErrorHandler() ) ¶

Similar to parse() , but parses from a buffer string received as a parameter. string must be a str instance or a bytes-like object .

Changed in version 3.5: Added support of str instances.

A typical SAX application uses three kinds of objects: readers, handlers and input sources. “Reader” in this context is another term for parser, i.e. some piece of code that reads the bytes or characters from the input source, and produces a sequence of events. The events then get distributed to the handler objects, i.e. the reader invokes a method on the handler. A SAX application must therefore obtain a reader object, create or open the input sources, create the handlers, and connect these objects all together. As the final step of preparation, the reader is called to parse the input. During parsing, methods on the handler objects are called based on structural and syntactic events from the input data.

For these objects, only the interfaces are relevant; they are normally not instantiated by the application itself. Since Python does not have an explicit notion of interface, they are formally introduced as classes, but applications may use implementations which do not inherit from the provided classes. The InputSource , Locator , Attributes , AttributesNS , and XMLReader interfaces are defined in the module xml.sax.xmlreader . The handler interfaces are defined in xml.sax.handler . For convenience, InputSource (which is often instantiated directly) and the handler classes are also available from xml.sax . These interfaces are described below.

In addition to these classes, xml.sax provides the following exception classes.

exception xml.sax. SAXException ( msg , exception = None ) ¶

Encapsulate an XML error or warning. This class can contain basic error or warning information from either the XML parser or the application: it can be subclassed to provide additional functionality or to add localization. Note that although the handlers defined in the ErrorHandler interface receive instances of this exception, it is not required to actually raise the exception — it is also useful as a container for information.

When instantiated, msg should be a human-readable description of the error. The optional exception parameter, if given, should be None or an exception that was caught by the parsing code and is being passed along as information.

This is the base class for the other SAX exception classes.

exception xml.sax. SAXParseException ( msg , exception , locator ) ¶

Subclass of SAXException raised on parse errors. Instances of this class are passed to the methods of the SAX ErrorHandler interface to provide information about the parse error. This class supports the SAX Locator interface as well as the SAXException interface.

exception xml.sax. SAXNotRecognizedException ( msg , exception = None ) ¶

Subclass of SAXException raised when a SAX XMLReader is confronted with an unrecognized feature or property. SAX applications and extensions may use this class for similar purposes.

exception xml.sax. SAXNotSupportedException ( msg , exception = None ) ¶

Subclass of SAXException raised when a SAX XMLReader is asked to enable a feature that is not supported, or to set a property to a value that the implementation does not support. SAX applications and extensions may use this class for similar purposes.

This site is the focal point for the definition of the SAX API. It provides a Java implementation and online documentation. Links to implementations and historical information are also available.

Definitions of the interfaces for application-provided objects.

Convenience functions for use in SAX applications.

Definitions of the interfaces for parser-provided objects.

SAXException Objects¶

The SAXException exception class supports the following methods:

Return a human-readable message describing the error condition.

Return an encapsulated exception object, or None .

Источник

xml.sax.saxutils — SAX Utilities¶

The module xml.sax.saxutils contains a number of classes and functions that are commonly useful when creating SAX applications, either in direct use, or as base classes.

xml.sax.saxutils. escape ( data , entities = <> ) ¶

Escape ‘&’ , » in a string of data.

You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. The characters ‘&’ , » are always escaped, even if entities is provided.

xml.sax.saxutils. unescape ( data , entities = <> ) ¶

Unescape ‘&’ , ‘<‘ , and ‘>’ in a string of data.

You can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. ‘&amp’ , ‘<‘ , and ‘>’ are always unescaped, even if entities is provided.

xml.sax.saxutils. quoteattr ( data , entities = <> ) ¶

Similar to escape() , but also prepares data to be used as an attribute value. The return value is a quoted version of data with any additional required replacements. quoteattr() will select a quote character based on the content of data, attempting to avoid encoding any quote characters in the string. If both single- and double-quote characters are already in data, the double-quote characters will be encoded and data will be wrapped in double-quotes. The resulting string can be used directly as an attribute value:

>>> print(«%s % quoteattr(«ab ‘ cd ef»))

This function is useful when generating attribute values for HTML or any SGML using the reference concrete syntax.

class xml.sax.saxutils. XMLGenerator ( out = None , encoding = ‘iso-8859-1’ , short_empty_elements = False ) ¶

This class implements the ContentHandler interface by writing SAX events back into an XML document. In other words, using an XMLGenerator as the content handler will reproduce the original document being parsed. out should be a file-like object which will default to sys.stdout. encoding is the encoding of the output stream which defaults to ‘iso-8859-1’ . short_empty_elements controls the formatting of elements that contain no content: if False (the default) they are emitted as a pair of start/end tags, if set to True they are emitted as a single self-closed tag.

New in version 3.2: The short_empty_elements parameter.

This class is designed to sit between an XMLReader and the client application’s event handlers. By default, it does nothing but pass requests up to the reader and events on to the handlers unmodified, but subclasses can override specific methods to modify the event stream or the configuration requests as they pass through.

xml.sax.saxutils. prepare_input_source ( source , base = » ) ¶

This function takes an input source and an optional base URL and returns a fully resolved InputSource object ready for reading. The input source can be given as a string, a file-like object, or an InputSource object; parsers will use this function to implement the polymorphic source argument to their parse() method.

Источник

Читайте также:  Перемножение всех элементов массива python
Оцените статью