doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
xmlparser.UseForeignDTD([flag]) Calling this with a true value for flag (the default) will cause Expat to call the ExternalEntityRefHandler with None for all arguments to allow an alternate DTD to be loaded. If the document does not contain a document type declaration, the ExternalEntityRefHandler will still be called, but the StartDoctypeDeclHandler and EndDoctypeDeclHandler will not be called. Passing a false value for flag will cancel a previous call that passed a true value, but otherwise has no effect. This method can only be called before the Parse() or ParseFile() methods are called; calling it after either of those have been called causes ExpatError to be raised with the code attribute set to errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING].
python.library.pyexpat#xml.parsers.expat.xmlparser.UseForeignDTD
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 1 if the document is declared standalone, 0 if it is declared not to be standalone, or -1 if the standalone clause was omitted. This is only available with Expat version 1.95.0 or newer.
python.library.pyexpat#xml.parsers.expat.xmlparser.XmlDeclHandler
xml.parsers.expat.XMLParserType The type of the return values from the ParserCreate() function.
python.library.pyexpat#xml.parsers.expat.XMLParserType
xml.sax — Support for SAX2 parsers Source code: Lib/xml/sax/__init__.py 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. Warning 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. xml.sax.parse(filename_or_stream, handler, error_handler=handler.ErrorHandler()) 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. See also SAX: The Simple API for XML 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. Module xml.sax.handler Definitions of the interfaces for application-provided objects. Module xml.sax.saxutils Convenience functions for use in SAX applications. Module xml.sax.xmlreader Definitions of the interfaces for parser-provided objects. SAXException Objects The SAXException exception class supports the following methods: SAXException.getMessage() Return a human-readable message describing the error condition. SAXException.getException() Return an encapsulated exception object, or None.
python.library.xml.sax
xml.sax.handler — Base classes for SAX handlers Source code: Lib/xml/sax/handler.py The SAX API defines four kinds of handlers: content handlers, DTD handlers, error handlers, and entity resolvers. Applications normally only need to implement those interfaces whose events they are interested in; they can implement the interfaces in a single object or in multiple objects. Handler implementations should inherit from the base classes provided in the module xml.sax.handler, so that all methods get default implementations. class xml.sax.handler.ContentHandler This is the main callback interface in SAX, and the one most important to applications. The order of events in this interface mirrors the order of the information in the document. class xml.sax.handler.DTDHandler Handle DTD events. This interface specifies only those DTD events required for basic parsing (unparsed entities and attributes). class xml.sax.handler.EntityResolver Basic interface for resolving entities. If you create an object implementing this interface, then register the object with your Parser, the parser will call the method in your object to resolve all external entities. class xml.sax.handler.ErrorHandler Interface used by the parser to present error and warning messages to the application. The methods of this object control whether errors are immediately converted to exceptions or are handled in some other way. In addition to these classes, xml.sax.handler provides symbolic constants for the feature and property names. xml.sax.handler.feature_namespaces xml.sax.handler.feature_namespace_prefixes xml.sax.handler.feature_string_interning xml.sax.handler.feature_validation xml.sax.handler.feature_external_ges xml.sax.handler.feature_external_pes xml.sax.handler.all_features List of all features. xml.sax.handler.property_lexical_handler xml.sax.handler.property_declaration_handler xml.sax.handler.property_dom_node xml.sax.handler.property_xml_string xml.sax.handler.all_properties List of all known property names. ContentHandler Objects Users are expected to subclass ContentHandler to support their application. The following methods are called by the parser on the appropriate events in the input document: ContentHandler.setDocumentLocator(locator) Called by the parser to give the application a locator for locating the origin of document events. SAX parsers are strongly encouraged (though not absolutely required) to supply a locator: if it does so, it must supply the locator to the application by invoking this method before invoking any of the other methods in the DocumentHandler interface. The locator allows the application to determine the end position of any document-related event, even if the parser is not reporting an error. Typically, the application will use this information for reporting its own errors (such as character content that does not match an application’s business rules). The information returned by the locator is probably not sufficient for use with a search engine. Note that the locator will return correct information only during the invocation of the events in this interface. The application should not attempt to use it at any other time. ContentHandler.startDocument() Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator()). ContentHandler.endDocument() Receive notification of the end of a document. The SAX parser will invoke this method only once, and it will be the last method invoked during the parse. The parser shall not invoke this method until it has either abandoned parsing (because of an unrecoverable error) or reached the end of input. ContentHandler.startPrefixMapping(prefix, uri) Begin the scope of a prefix-URI Namespace mapping. The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the feature_namespaces feature is enabled (the default). There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the startPrefixMapping() and endPrefixMapping() events supply the information to the application to expand prefixes in those contexts itself, if necessary. Note that startPrefixMapping() and endPrefixMapping() events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping() events will occur before the corresponding startElement() event, and all endPrefixMapping() events will occur after the corresponding endElement() event, but their order is not guaranteed. ContentHandler.endPrefixMapping(prefix) End the scope of a prefix-URI mapping. See startPrefixMapping() for details. This event will always occur after the corresponding endElement() event, but the order of endPrefixMapping() events is not otherwise guaranteed. ContentHandler.startElement(name, attrs) Signals the start of an element in non-namespace mode. The name parameter contains the raw XML 1.0 name of the element type as a string and the attrs parameter holds an object of the Attributes interface (see The Attributes Interface) containing the attributes of the element. The object passed as attrs may be re-used by the parser; holding on to a reference to it is not a reliable way to keep a copy of the attributes. To keep a copy of the attributes, use the copy() method of the attrs object. ContentHandler.endElement(name) Signals the end of an element in non-namespace mode. The name parameter contains the name of the element type, just as with the startElement() event. ContentHandler.startElementNS(name, qname, attrs) Signals the start of an element in namespace mode. The name parameter contains the name of the element type as a (uri, localname) tuple, the qname parameter contains the raw XML 1.0 name used in the source document, and the attrs parameter holds an instance of the AttributesNS interface (see The AttributesNS Interface) containing the attributes of the element. If no namespace is associated with the element, the uri component of name will be None. The object passed as attrs may be re-used by the parser; holding on to a reference to it is not a reliable way to keep a copy of the attributes. To keep a copy of the attributes, use the copy() method of the attrs object. Parsers may set the qname parameter to None, unless the feature_namespace_prefixes feature is activated. ContentHandler.endElementNS(name, qname) Signals the end of an element in namespace mode. The name parameter contains the name of the element type, just as with the startElementNS() method, likewise the qname parameter. ContentHandler.characters(content) Receive notification of character data. The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information. content may be a string or bytes instance; the expat reader module always produces strings. Note The earlier SAX 1 interface provided by the Python XML Special Interest Group used a more Java-like interface for this method. Since most parsers used from Python did not take advantage of the older interface, the simpler signature was chosen to replace it. To convert old code to the new interface, use content instead of slicing content with the old offset and length parameters. ContentHandler.ignorableWhitespace(whitespace) Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models. SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information. ContentHandler.processingInstruction(target, data) Receive notification of a processing instruction. The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element. A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method. ContentHandler.skippedEntity(name) Receive notification of a skipped entity. The Parser will invoke this method once for each entity skipped. Non-validating processors may skip entities if they have not seen the declarations (because, for example, the entity was declared in an external DTD subset). All processors may skip external entities, depending on the values of the feature_external_ges and the feature_external_pes properties. DTDHandler Objects DTDHandler instances provide the following methods: DTDHandler.notationDecl(name, publicId, systemId) Handle a notation declaration event. DTDHandler.unparsedEntityDecl(name, publicId, systemId, ndata) Handle an unparsed entity declaration event. EntityResolver Objects EntityResolver.resolveEntity(publicId, systemId) Resolve the system identifier of an entity and return either the system identifier to read from as a string, or an InputSource to read from. The default implementation returns systemId. ErrorHandler Objects Objects with this interface are used to receive error and warning information from the XMLReader. If you create an object that implements this interface, then register the object with your XMLReader, the parser will call the methods in your object to report all warnings and errors. There are three levels of errors available: warnings, (possibly) recoverable errors, and unrecoverable errors. All methods take a SAXParseException as the only parameter. Errors and warnings may be converted to an exception by raising the passed-in exception object. ErrorHandler.error(exception) Called when the parser encounters a recoverable error. If this method does not raise an exception, parsing may continue, but further document information should not be expected by the application. Allowing the parser to continue may allow additional errors to be discovered in the input document. ErrorHandler.fatalError(exception) Called when the parser encounters an error it cannot recover from; parsing is expected to terminate when this method returns. ErrorHandler.warning(exception) Called when the parser presents minor warning information to the application. Parsing is expected to continue when this method returns, and document information will continue to be passed to the application. Raising an exception in this method will cause parsing to end.
python.library.xml.sax.handler
xml.sax.handler.all_features List of all features.
python.library.xml.sax.handler#xml.sax.handler.all_features
xml.sax.handler.all_properties List of all known property names.
python.library.xml.sax.handler#xml.sax.handler.all_properties
class xml.sax.handler.ContentHandler This is the main callback interface in SAX, and the one most important to applications. The order of events in this interface mirrors the order of the information in the document.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler
ContentHandler.characters(content) Receive notification of character data. The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information. content may be a string or bytes instance; the expat reader module always produces strings. Note The earlier SAX 1 interface provided by the Python XML Special Interest Group used a more Java-like interface for this method. Since most parsers used from Python did not take advantage of the older interface, the simpler signature was chosen to replace it. To convert old code to the new interface, use content instead of slicing content with the old offset and length parameters.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.characters
ContentHandler.endDocument() Receive notification of the end of a document. The SAX parser will invoke this method only once, and it will be the last method invoked during the parse. The parser shall not invoke this method until it has either abandoned parsing (because of an unrecoverable error) or reached the end of input.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.endDocument
ContentHandler.endElement(name) Signals the end of an element in non-namespace mode. The name parameter contains the name of the element type, just as with the startElement() event.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.endElement
ContentHandler.endElementNS(name, qname) Signals the end of an element in namespace mode. The name parameter contains the name of the element type, just as with the startElementNS() method, likewise the qname parameter.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.endElementNS
ContentHandler.endPrefixMapping(prefix) End the scope of a prefix-URI mapping. See startPrefixMapping() for details. This event will always occur after the corresponding endElement() event, but the order of endPrefixMapping() events is not otherwise guaranteed.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.endPrefixMapping
ContentHandler.ignorableWhitespace(whitespace) Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models. SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.ignorableWhitespace
ContentHandler.processingInstruction(target, data) Receive notification of a processing instruction. The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element. A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.processingInstruction
ContentHandler.setDocumentLocator(locator) Called by the parser to give the application a locator for locating the origin of document events. SAX parsers are strongly encouraged (though not absolutely required) to supply a locator: if it does so, it must supply the locator to the application by invoking this method before invoking any of the other methods in the DocumentHandler interface. The locator allows the application to determine the end position of any document-related event, even if the parser is not reporting an error. Typically, the application will use this information for reporting its own errors (such as character content that does not match an application’s business rules). The information returned by the locator is probably not sufficient for use with a search engine. Note that the locator will return correct information only during the invocation of the events in this interface. The application should not attempt to use it at any other time.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.setDocumentLocator
ContentHandler.skippedEntity(name) Receive notification of a skipped entity. The Parser will invoke this method once for each entity skipped. Non-validating processors may skip entities if they have not seen the declarations (because, for example, the entity was declared in an external DTD subset). All processors may skip external entities, depending on the values of the feature_external_ges and the feature_external_pes properties.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.skippedEntity
ContentHandler.startDocument() Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator()).
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.startDocument
ContentHandler.startElement(name, attrs) Signals the start of an element in non-namespace mode. The name parameter contains the raw XML 1.0 name of the element type as a string and the attrs parameter holds an object of the Attributes interface (see The Attributes Interface) containing the attributes of the element. The object passed as attrs may be re-used by the parser; holding on to a reference to it is not a reliable way to keep a copy of the attributes. To keep a copy of the attributes, use the copy() method of the attrs object.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.startElement
ContentHandler.startElementNS(name, qname, attrs) Signals the start of an element in namespace mode. The name parameter contains the name of the element type as a (uri, localname) tuple, the qname parameter contains the raw XML 1.0 name used in the source document, and the attrs parameter holds an instance of the AttributesNS interface (see The AttributesNS Interface) containing the attributes of the element. If no namespace is associated with the element, the uri component of name will be None. The object passed as attrs may be re-used by the parser; holding on to a reference to it is not a reliable way to keep a copy of the attributes. To keep a copy of the attributes, use the copy() method of the attrs object. Parsers may set the qname parameter to None, unless the feature_namespace_prefixes feature is activated.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.startElementNS
ContentHandler.startPrefixMapping(prefix, uri) Begin the scope of a prefix-URI Namespace mapping. The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the feature_namespaces feature is enabled (the default). There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the startPrefixMapping() and endPrefixMapping() events supply the information to the application to expand prefixes in those contexts itself, if necessary. Note that startPrefixMapping() and endPrefixMapping() events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping() events will occur before the corresponding startElement() event, and all endPrefixMapping() events will occur after the corresponding endElement() event, but their order is not guaranteed.
python.library.xml.sax.handler#xml.sax.handler.ContentHandler.startPrefixMapping
class xml.sax.handler.DTDHandler Handle DTD events. This interface specifies only those DTD events required for basic parsing (unparsed entities and attributes).
python.library.xml.sax.handler#xml.sax.handler.DTDHandler
DTDHandler.notationDecl(name, publicId, systemId) Handle a notation declaration event.
python.library.xml.sax.handler#xml.sax.handler.DTDHandler.notationDecl
DTDHandler.unparsedEntityDecl(name, publicId, systemId, ndata) Handle an unparsed entity declaration event.
python.library.xml.sax.handler#xml.sax.handler.DTDHandler.unparsedEntityDecl
class xml.sax.handler.EntityResolver Basic interface for resolving entities. If you create an object implementing this interface, then register the object with your Parser, the parser will call the method in your object to resolve all external entities.
python.library.xml.sax.handler#xml.sax.handler.EntityResolver
EntityResolver.resolveEntity(publicId, systemId) Resolve the system identifier of an entity and return either the system identifier to read from as a string, or an InputSource to read from. The default implementation returns systemId.
python.library.xml.sax.handler#xml.sax.handler.EntityResolver.resolveEntity
class xml.sax.handler.ErrorHandler Interface used by the parser to present error and warning messages to the application. The methods of this object control whether errors are immediately converted to exceptions or are handled in some other way.
python.library.xml.sax.handler#xml.sax.handler.ErrorHandler
ErrorHandler.error(exception) Called when the parser encounters a recoverable error. If this method does not raise an exception, parsing may continue, but further document information should not be expected by the application. Allowing the parser to continue may allow additional errors to be discovered in the input document.
python.library.xml.sax.handler#xml.sax.handler.ErrorHandler.error
ErrorHandler.fatalError(exception) Called when the parser encounters an error it cannot recover from; parsing is expected to terminate when this method returns.
python.library.xml.sax.handler#xml.sax.handler.ErrorHandler.fatalError
ErrorHandler.warning(exception) Called when the parser presents minor warning information to the application. Parsing is expected to continue when this method returns, and document information will continue to be passed to the application. Raising an exception in this method will cause parsing to end.
python.library.xml.sax.handler#xml.sax.handler.ErrorHandler.warning
xml.sax.handler.feature_external_ges
python.library.xml.sax.handler#xml.sax.handler.feature_external_ges
xml.sax.handler.feature_external_pes
python.library.xml.sax.handler#xml.sax.handler.feature_external_pes
xml.sax.handler.feature_namespaces
python.library.xml.sax.handler#xml.sax.handler.feature_namespaces
xml.sax.handler.feature_namespace_prefixes
python.library.xml.sax.handler#xml.sax.handler.feature_namespace_prefixes
xml.sax.handler.feature_string_interning
python.library.xml.sax.handler#xml.sax.handler.feature_string_interning
xml.sax.handler.feature_validation
python.library.xml.sax.handler#xml.sax.handler.feature_validation
xml.sax.handler.property_declaration_handler
python.library.xml.sax.handler#xml.sax.handler.property_declaration_handler
xml.sax.handler.property_dom_node
python.library.xml.sax.handler#xml.sax.handler.property_dom_node
xml.sax.handler.property_lexical_handler
python.library.xml.sax.handler#xml.sax.handler.property_lexical_handler
xml.sax.handler.property_xml_string
python.library.xml.sax.handler#xml.sax.handler.property_xml_string
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.
python.library.xml.sax#xml.sax.make_parser
xml.sax.parse(filename_or_stream, handler, error_handler=handler.ErrorHandler()) 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.
python.library.xml.sax#xml.sax.parse
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.
python.library.xml.sax#xml.sax.parseString
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.
python.library.xml.sax#xml.sax.SAXException
SAXException.getException() Return an encapsulated exception object, or None.
python.library.xml.sax#xml.sax.SAXException.getException
SAXException.getMessage() Return a human-readable message describing the error condition.
python.library.xml.sax#xml.sax.SAXException.getMessage
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.
python.library.xml.sax#xml.sax.SAXNotRecognizedException
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.
python.library.xml.sax#xml.sax.SAXNotSupportedException
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.
python.library.xml.sax#xml.sax.SAXParseException
xml.sax.saxutils — SAX Utilities Source code: Lib/xml/sax/saxutils.py 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 '&', '<', and '>' 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 '&', '<' and '>' are always escaped, even if entities is provided. xml.sax.saxutils.unescape(data, entities={}) Unescape '&amp;', '&lt;', and '&gt;' 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', '&lt;', and '&gt;' 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("<element attr=%s>" % quoteattr("ab ' cd \" ef")) <element attr="ab ' cd &quot; 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. class xml.sax.saxutils.XMLFilterBase(base) 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.library.xml.sax.utils
xml.sax.saxutils.escape(data, entities={}) Escape '&', '<', and '>' 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 '&', '<' and '>' are always escaped, even if entities is provided.
python.library.xml.sax.utils#xml.sax.saxutils.escape
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.library.xml.sax.utils#xml.sax.saxutils.prepare_input_source
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("<element attr=%s>" % quoteattr("ab ' cd \" ef")) <element attr="ab ' cd &quot; ef"> This function is useful when generating attribute values for HTML or any SGML using the reference concrete syntax.
python.library.xml.sax.utils#xml.sax.saxutils.quoteattr
xml.sax.saxutils.unescape(data, entities={}) Unescape '&amp;', '&lt;', and '&gt;' 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', '&lt;', and '&gt;' are always unescaped, even if entities is provided.
python.library.xml.sax.utils#xml.sax.saxutils.unescape
class xml.sax.saxutils.XMLFilterBase(base) 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.
python.library.xml.sax.utils#xml.sax.saxutils.XMLFilterBase
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.
python.library.xml.sax.utils#xml.sax.saxutils.XMLGenerator
xml.sax.xmlreader — Interface for XML parsers Source code: Lib/xml/sax/xmlreader.py SAX parsers implement the XMLReader interface. They are implemented in a Python module, which must provide a function create_parser(). This function is invoked by xml.sax.make_parser() with no arguments to create a new parser object. class xml.sax.xmlreader.XMLReader Base class which can be inherited by SAX parsers. class xml.sax.xmlreader.IncrementalParser In some cases, it is desirable not to parse an input source at once, but to feed chunks of the document as they get available. Note that the reader will normally not read the entire file, but read it in chunks as well; still parse() won’t return until the entire document is processed. So these interfaces should be used if the blocking behaviour of parse() is not desirable. When the parser is instantiated it is ready to begin accepting data from the feed method immediately. After parsing has been finished with a call to close the reset method must be called to make the parser ready to accept new data, either from feed or using the parse method. Note that these methods must not be called during parsing, that is, after parse has been called and before it returns. By default, the class also implements the parse method of the XMLReader interface using the feed, close and reset methods of the IncrementalParser interface as a convenience to SAX 2.0 driver writers. class xml.sax.xmlreader.Locator Interface for associating a SAX event with a document location. A locator object will return valid results only during calls to DocumentHandler methods; at any other time, the results are unpredictable. If information is not available, methods may return None. class xml.sax.xmlreader.InputSource(system_id=None) Encapsulation of the information needed by the XMLReader to read entities. This class may include information about the public identifier, system identifier, byte stream (possibly with character encoding information) and/or the character stream of an entity. Applications will create objects of this class for use in the XMLReader.parse() method and for returning from EntityResolver.resolveEntity. An InputSource belongs to the application, the XMLReader is not allowed to modify InputSource objects passed to it from the application, although it may make copies and modify those. class xml.sax.xmlreader.AttributesImpl(attrs) This is an implementation of the Attributes interface (see section The Attributes Interface). This is a dictionary-like object which represents the element attributes in a startElement() call. In addition to the most useful dictionary operations, it supports a number of other methods as described by the interface. Objects of this class should be instantiated by readers; attrs must be a dictionary-like object containing a mapping from attribute names to attribute values. class xml.sax.xmlreader.AttributesNSImpl(attrs, qnames) Namespace-aware variant of AttributesImpl, which will be passed to startElementNS(). It is derived from AttributesImpl, but understands attribute names as two-tuples of namespaceURI and localname. In addition, it provides a number of methods expecting qualified names as they appear in the original document. This class implements the AttributesNS interface (see section The AttributesNS Interface). XMLReader Objects The XMLReader interface supports the following methods: XMLReader.parse(source) Process an input source, producing SAX events. The source object can be a system identifier (a string identifying the input source – typically a file name or a URL), a pathlib.Path or path-like object, or an InputSource object. When parse() returns, the input is completely processed, and the parser object can be discarded or reset. Changed in version 3.5: Added support of character streams. Changed in version 3.8: Added support of path-like objects. XMLReader.getContentHandler() Return the current ContentHandler. XMLReader.setContentHandler(handler) Set the current ContentHandler. If no ContentHandler is set, content events will be discarded. XMLReader.getDTDHandler() Return the current DTDHandler. XMLReader.setDTDHandler(handler) Set the current DTDHandler. If no DTDHandler is set, DTD events will be discarded. XMLReader.getEntityResolver() Return the current EntityResolver. XMLReader.setEntityResolver(handler) Set the current EntityResolver. If no EntityResolver is set, attempts to resolve an external entity will result in opening the system identifier for the entity, and fail if it is not available. XMLReader.getErrorHandler() Return the current ErrorHandler. XMLReader.setErrorHandler(handler) Set the current error handler. If no ErrorHandler is set, errors will be raised as exceptions, and warnings will be printed. XMLReader.setLocale(locale) Allow an application to set the locale for errors and warnings. SAX parsers are not required to provide localization for errors and warnings; if they cannot support the requested locale, however, they must raise a SAX exception. Applications may request a locale change in the middle of a parse. XMLReader.getFeature(featurename) Return the current setting for feature featurename. If the feature is not recognized, SAXNotRecognizedException is raised. The well-known featurenames are listed in the module xml.sax.handler. XMLReader.setFeature(featurename, value) Set the featurename to value. If the feature is not recognized, SAXNotRecognizedException is raised. If the feature or its setting is not supported by the parser, SAXNotSupportedException is raised. XMLReader.getProperty(propertyname) Return the current setting for property propertyname. If the property is not recognized, a SAXNotRecognizedException is raised. The well-known propertynames are listed in the module xml.sax.handler. XMLReader.setProperty(propertyname, value) Set the propertyname to value. If the property is not recognized, SAXNotRecognizedException is raised. If the property or its setting is not supported by the parser, SAXNotSupportedException is raised. IncrementalParser Objects Instances of IncrementalParser offer the following additional methods: IncrementalParser.feed(data) Process a chunk of data. IncrementalParser.close() Assume the end of the document. That will check well-formedness conditions that can be checked only at the end, invoke handlers, and may clean up resources allocated during parsing. IncrementalParser.reset() This method is called after close has been called to reset the parser so that it is ready to parse new documents. The results of calling parse or feed after close without calling reset are undefined. Locator Objects Instances of Locator provide these methods: Locator.getColumnNumber() Return the column number where the current event begins. Locator.getLineNumber() Return the line number where the current event begins. Locator.getPublicId() Return the public identifier for the current event. Locator.getSystemId() Return the system identifier for the current event. InputSource Objects InputSource.setPublicId(id) Sets the public identifier of this InputSource. InputSource.getPublicId() Returns the public identifier of this InputSource. InputSource.setSystemId(id) Sets the system identifier of this InputSource. InputSource.getSystemId() Returns the system identifier of this InputSource. InputSource.setEncoding(encoding) Sets the character encoding of this InputSource. The encoding must be a string acceptable for an XML encoding declaration (see section 4.3.3 of the XML recommendation). The encoding attribute of the InputSource is ignored if the InputSource also contains a character stream. InputSource.getEncoding() Get the character encoding of this InputSource. InputSource.setByteStream(bytefile) Set the byte stream (a binary file) for this input source. The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself. If the application knows the character encoding of the byte stream, it should set it with the setEncoding method. InputSource.getByteStream() Get the byte stream for this input source. The getEncoding method will return the character encoding for this byte stream, or None if unknown. InputSource.setCharacterStream(charfile) Set the character stream (a text file) for this input source. If there is a character stream specified, the SAX parser will ignore any byte stream and will not attempt to open a URI connection to the system identifier. InputSource.getCharacterStream() Get the character stream for this input source. The Attributes Interface Attributes objects implement a portion of the mapping protocol, including the methods copy(), get(), __contains__(), items(), keys(), and values(). The following methods are also provided: Attributes.getLength() Return the number of attributes. Attributes.getNames() Return the names of the attributes. Attributes.getType(name) Returns the type of the attribute name, which is normally 'CDATA'. Attributes.getValue(name) Return the value of attribute name. The AttributesNS Interface This interface is a subtype of the Attributes interface (see section The Attributes Interface). All methods supported by that interface are also available on AttributesNS objects. The following methods are also available: AttributesNS.getValueByQName(name) Return the value for a qualified name. AttributesNS.getNameByQName(name) Return the (namespace, localname) pair for a qualified name. AttributesNS.getQNameByName(name) Return the qualified name for a (namespace, localname) pair. AttributesNS.getQNames() Return the qualified names of all attributes.
python.library.xml.sax.reader
Attributes.getLength() Return the number of attributes.
python.library.xml.sax.reader#xml.sax.xmlreader.Attributes.getLength
Attributes.getNames() Return the names of the attributes.
python.library.xml.sax.reader#xml.sax.xmlreader.Attributes.getNames
Attributes.getType(name) Returns the type of the attribute name, which is normally 'CDATA'.
python.library.xml.sax.reader#xml.sax.xmlreader.Attributes.getType
Attributes.getValue(name) Return the value of attribute name.
python.library.xml.sax.reader#xml.sax.xmlreader.Attributes.getValue
class xml.sax.xmlreader.AttributesImpl(attrs) This is an implementation of the Attributes interface (see section The Attributes Interface). This is a dictionary-like object which represents the element attributes in a startElement() call. In addition to the most useful dictionary operations, it supports a number of other methods as described by the interface. Objects of this class should be instantiated by readers; attrs must be a dictionary-like object containing a mapping from attribute names to attribute values.
python.library.xml.sax.reader#xml.sax.xmlreader.AttributesImpl
AttributesNS.getNameByQName(name) Return the (namespace, localname) pair for a qualified name.
python.library.xml.sax.reader#xml.sax.xmlreader.AttributesNS.getNameByQName
AttributesNS.getQNameByName(name) Return the qualified name for a (namespace, localname) pair.
python.library.xml.sax.reader#xml.sax.xmlreader.AttributesNS.getQNameByName
AttributesNS.getQNames() Return the qualified names of all attributes.
python.library.xml.sax.reader#xml.sax.xmlreader.AttributesNS.getQNames
AttributesNS.getValueByQName(name) Return the value for a qualified name.
python.library.xml.sax.reader#xml.sax.xmlreader.AttributesNS.getValueByQName
class xml.sax.xmlreader.AttributesNSImpl(attrs, qnames) Namespace-aware variant of AttributesImpl, which will be passed to startElementNS(). It is derived from AttributesImpl, but understands attribute names as two-tuples of namespaceURI and localname. In addition, it provides a number of methods expecting qualified names as they appear in the original document. This class implements the AttributesNS interface (see section The AttributesNS Interface).
python.library.xml.sax.reader#xml.sax.xmlreader.AttributesNSImpl
class xml.sax.xmlreader.IncrementalParser In some cases, it is desirable not to parse an input source at once, but to feed chunks of the document as they get available. Note that the reader will normally not read the entire file, but read it in chunks as well; still parse() won’t return until the entire document is processed. So these interfaces should be used if the blocking behaviour of parse() is not desirable. When the parser is instantiated it is ready to begin accepting data from the feed method immediately. After parsing has been finished with a call to close the reset method must be called to make the parser ready to accept new data, either from feed or using the parse method. Note that these methods must not be called during parsing, that is, after parse has been called and before it returns. By default, the class also implements the parse method of the XMLReader interface using the feed, close and reset methods of the IncrementalParser interface as a convenience to SAX 2.0 driver writers.
python.library.xml.sax.reader#xml.sax.xmlreader.IncrementalParser
IncrementalParser.close() Assume the end of the document. That will check well-formedness conditions that can be checked only at the end, invoke handlers, and may clean up resources allocated during parsing.
python.library.xml.sax.reader#xml.sax.xmlreader.IncrementalParser.close
IncrementalParser.feed(data) Process a chunk of data.
python.library.xml.sax.reader#xml.sax.xmlreader.IncrementalParser.feed
IncrementalParser.reset() This method is called after close has been called to reset the parser so that it is ready to parse new documents. The results of calling parse or feed after close without calling reset are undefined.
python.library.xml.sax.reader#xml.sax.xmlreader.IncrementalParser.reset
class xml.sax.xmlreader.InputSource(system_id=None) Encapsulation of the information needed by the XMLReader to read entities. This class may include information about the public identifier, system identifier, byte stream (possibly with character encoding information) and/or the character stream of an entity. Applications will create objects of this class for use in the XMLReader.parse() method and for returning from EntityResolver.resolveEntity. An InputSource belongs to the application, the XMLReader is not allowed to modify InputSource objects passed to it from the application, although it may make copies and modify those.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource
InputSource.getByteStream() Get the byte stream for this input source. The getEncoding method will return the character encoding for this byte stream, or None if unknown.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.getByteStream
InputSource.getCharacterStream() Get the character stream for this input source.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.getCharacterStream
InputSource.getEncoding() Get the character encoding of this InputSource.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.getEncoding
InputSource.getPublicId() Returns the public identifier of this InputSource.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.getPublicId
InputSource.getSystemId() Returns the system identifier of this InputSource.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.getSystemId
InputSource.setByteStream(bytefile) Set the byte stream (a binary file) for this input source. The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself. If the application knows the character encoding of the byte stream, it should set it with the setEncoding method.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.setByteStream
InputSource.setCharacterStream(charfile) Set the character stream (a text file) for this input source. If there is a character stream specified, the SAX parser will ignore any byte stream and will not attempt to open a URI connection to the system identifier.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.setCharacterStream
InputSource.setEncoding(encoding) Sets the character encoding of this InputSource. The encoding must be a string acceptable for an XML encoding declaration (see section 4.3.3 of the XML recommendation). The encoding attribute of the InputSource is ignored if the InputSource also contains a character stream.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.setEncoding
InputSource.setPublicId(id) Sets the public identifier of this InputSource.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.setPublicId
InputSource.setSystemId(id) Sets the system identifier of this InputSource.
python.library.xml.sax.reader#xml.sax.xmlreader.InputSource.setSystemId
class xml.sax.xmlreader.Locator Interface for associating a SAX event with a document location. A locator object will return valid results only during calls to DocumentHandler methods; at any other time, the results are unpredictable. If information is not available, methods may return None.
python.library.xml.sax.reader#xml.sax.xmlreader.Locator
Locator.getColumnNumber() Return the column number where the current event begins.
python.library.xml.sax.reader#xml.sax.xmlreader.Locator.getColumnNumber
Locator.getLineNumber() Return the line number where the current event begins.
python.library.xml.sax.reader#xml.sax.xmlreader.Locator.getLineNumber
Locator.getPublicId() Return the public identifier for the current event.
python.library.xml.sax.reader#xml.sax.xmlreader.Locator.getPublicId
Locator.getSystemId() Return the system identifier for the current event.
python.library.xml.sax.reader#xml.sax.xmlreader.Locator.getSystemId
class xml.sax.xmlreader.XMLReader Base class which can be inherited by SAX parsers.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader
XMLReader.getContentHandler() Return the current ContentHandler.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.getContentHandler
XMLReader.getDTDHandler() Return the current DTDHandler.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.getDTDHandler
XMLReader.getEntityResolver() Return the current EntityResolver.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.getEntityResolver
XMLReader.getErrorHandler() Return the current ErrorHandler.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.getErrorHandler
XMLReader.getFeature(featurename) Return the current setting for feature featurename. If the feature is not recognized, SAXNotRecognizedException is raised. The well-known featurenames are listed in the module xml.sax.handler.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.getFeature
XMLReader.getProperty(propertyname) Return the current setting for property propertyname. If the property is not recognized, a SAXNotRecognizedException is raised. The well-known propertynames are listed in the module xml.sax.handler.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.getProperty
XMLReader.parse(source) Process an input source, producing SAX events. The source object can be a system identifier (a string identifying the input source – typically a file name or a URL), a pathlib.Path or path-like object, or an InputSource object. When parse() returns, the input is completely processed, and the parser object can be discarded or reset. Changed in version 3.5: Added support of character streams. Changed in version 3.8: Added support of path-like objects.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.parse
XMLReader.setContentHandler(handler) Set the current ContentHandler. If no ContentHandler is set, content events will be discarded.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.setContentHandler
XMLReader.setDTDHandler(handler) Set the current DTDHandler. If no DTDHandler is set, DTD events will be discarded.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.setDTDHandler
XMLReader.setEntityResolver(handler) Set the current EntityResolver. If no EntityResolver is set, attempts to resolve an external entity will result in opening the system identifier for the entity, and fail if it is not available.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.setEntityResolver
XMLReader.setErrorHandler(handler) Set the current error handler. If no ErrorHandler is set, errors will be raised as exceptions, and warnings will be printed.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.setErrorHandler
XMLReader.setFeature(featurename, value) Set the featurename to value. If the feature is not recognized, SAXNotRecognizedException is raised. If the feature or its setting is not supported by the parser, SAXNotSupportedException is raised.
python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.setFeature