Package xmlschema_acue :: Package validators :: Module schema :: Class XMLSchemaBase

Class XMLSchemaBase

source code


Base class for an XML Schema instance.

:param source: an URI that reference to a resource or a file path or a file-like object or a string containing the schema or an Element or an ElementTree document. :type source: Element or ElementTree or str or file-like object :param namespace: is an optional argument that contains the URI of the namespace. When specified it must be equal to the *targetNamespace* declared in the schema. :type namespace: str or None :param validation: defines the XSD validation mode to use for build the schema, it's value can be 'strict', 'lax' or 'skip'. :type validation: str :param global_maps: is an optional argument containing an :class:`XsdGlobals` instance, a mediator object for sharing declaration data between dependents schema instances. :type global_maps: XsdGlobals or None :param converter: is an optional argument that can be an :class:`XMLSchemaConverter` subclass or instance, used for defining the default XML data converter for XML Schema instance. :type converter: XMLSchemaConverter or None :param locations: schema location hints for namespace imports. Can be a dictionary or a sequence of couples (namespace URI, resource URL). :type locations: dict or list or None :param base_url: is an optional base URL, used for the normalization of relative paths when the URL of the schema resource can't be obtained from the source argument. :type base_url: str or None :param defuse: defines when to defuse XML data. Can be 'always', 'remote' or 'never'. For default defuse only remote XML data. :type defuse: str or None :param timeout: the timeout in seconds for fetching resources. Default is `300`. :type timeout: int :param build: defines whether build the schema maps. Default is `True`. :type build: bool :param use_meta: if `True` the schema processor uses the package meta-schema, otherwise the meta-schema is added at the end. In the latter case the meta-schema is rebuilt if any base namespace has been overridden by an import. Ignored if the argument *global_maps* is provided. :type use_meta: bool

:cvar XSD_VERSION: store the XSD version (1.0 or 1.1). :vartype XSD_VERSION: str :cvar BUILDERS: a namedtuple with attributes related to schema components classes. Used for build local components within parsing methods. :vartype BUILDERS: namedtuple :cvar BUILDERS_MAP: a dictionary that maps from tag to class for XSD global components. Used for build global components within lookup functions. :vartype BUILDERS_MAP: dict :cvar BASE_SCHEMAS: a dictionary from namespace to schema resource for meta-schema bases. :vartype BASE_SCHEMAS: dict :cvar meta_schema: the XSD meta-schema instance. :vartype meta_schema: XMLSchema :cvar attribute_form_default: the schema's *attributeFormDefault* attribute, defaults to 'unqualified'. :vartype attribute_form_default: str :cvar element_form_default: the schema's *elementFormDefault* attribute, defaults to 'unqualified' :vartype element_form_default: str :cvar block_default: the schema's *blockDefault* attribute, defaults to ''. :vartype block_default: str :cvar final_default: the schema's *finalDefault* attribute, defaults to ''. :vartype final_default: str :cvar default_attributes: the XSD 1.1 schema's *defaultAttributes* attribute, defaults to ``None``. :vartype default_attributes: XsdAttributeGroup

:ivar target_namespace: is the *targetNamespace* of the schema, the namespace to which belong the declarations/definitions of the schema. If it's empty no namespace is associated with the schema. In this case the schema declarations can be reused from other namespaces as *chameleon* definitions. :vartype target_namespace: str :ivar validation: validation mode, can be 'strict', 'lax' or 'skip'. :vartype validation: str :ivar maps: XSD global declarations/definitions maps. This is an instance of :class:`XsdGlobal`, that store the global_maps argument or a new object when this argument is not provided. :vartype maps: XsdGlobals :ivar converter: the default converter used for XML data decoding/encoding. :vartype converter: XMLSchemaConverter :ivar locations: schema location hints. :vartype locations: NamespaceResourcesMap :ivar namespaces: a dictionary that maps from the prefixes used by the schema into namespace URI. :vartype namespaces: dict :ivar imports: a dictionary of namespace imports of the schema, that maps namespace URI to imported schema object, or `None` in case of unsuccessful import. :vartype imports: dict :ivar includes: a dictionary of included schemas, that maps a schema location to an included schema. It also comprehend schemas included by "xs:redefine" or "xs:override" statements. :vartype warnings: dict :ivar warnings: warning messages about failure of import and include elements. :vartype warnings: list

:ivar notations: `xsd:notation` declarations. :vartype notations: NamespaceView :ivar types: `xsd:simpleType` and `xsd:complexType` global declarations. :vartype types: NamespaceView :ivar attributes: `xsd:attribute` global declarations. :vartype attributes: NamespaceView :ivar attribute_groups: `xsd:attributeGroup` definitions. :vartype attribute_groups: NamespaceView :ivar groups: `xsd:group` global definitions. :vartype groups: NamespaceView :ivar elements: `xsd:element` global declarations. :vartype elements: NamespaceView

Instance Methods
 
__repr__(self) source code
 
__setattr__(self, name, value) source code
 
create_any_content_group(self, parent, name=None)
Creates a model group related to schema instance that accepts any content.
source code
 
create_any_attribute_group(self, parent, name=None)
Creates an attribute group related to schema instance that accepts any attribute.
source code
 
build(self)
Builds the schema XSD global maps.
source code
 
get_locations(self, namespace)
Get a list of location hints for a namespace.
source code

Inherited from xsdbase.XsdValidator: __str__, __unicode__

Inherited from xpath.ElementPathMixin: __getitem__

Class Methods
 
builtin_types(cls)
An accessor for XSD built-in types.
source code
 
create_schema(cls, *args, **kwargs)
Creates a new schema instance of the same class of the caller.
source code
Class Variables
  XSD_VERSION = None
  BUILDERS = None
  BUILDERS_MAP = None
  BASE_SCHEMAS = None
  meta_schema = None
  target_namespace = ''
  attribute_form_default = 'unqualified'
  element_form_default = 'unqualified'
  block_default = ''
  final_default = ''
  default_attributes = None

Inherited from xpath.ElementPathMixin: namespaces, tail, text, xpath_default_namespace

Method Details

__init__(self, source, namespace=None, validation='strict', global_maps=None, converter=None, locations=None, base_url=None, defuse='remote', timeout=300, build=True, use_meta=True)
(Constructor)

source code 
Decorators:
Overrides: xsdbase.XsdValidator.__init__

__iter__(self)

source code 
Decorators:
Overrides: xpath.ElementPathMixin.__iter__

__reversed__(self)

source code 
Decorators:
Overrides: xpath.ElementPathMixin.__reversed__

__len__(self)
(Length operator)

source code 
Decorators:
Overrides: xpath.ElementPathMixin.__len__

root(self)

source code 

Root element of the schema.

Decorators:
  • @property

get_text(self)

source code 

Gets the XSD text of the schema. If the source text is not available creates an encoded string representation of the XSD tree.

Decorators:

url(self)

source code 

Schema resource URL, is `None` if the schema is built from a string.

Decorators:
  • @property

base_url(self)

source code 

The base URL of the source of the schema.

Decorators:
  • @property

defuse(self)

source code 

Defines when to defuse XML data, can be 'always', 'remote' or 'never'.

Decorators:
  • @property

timeout(self)

source code 

Timeout in seconds for fetching resources.

Decorators:
  • @property

use_meta(self)

source code 

Returns `True` if the meta-schema is imported.

Decorators:
  • @property

tag(self)

source code 

Schema root tag. For compatibility with the ElementTree API.

Decorators:
  • @property
Overrides: xpath.ElementPathMixin.tag

id(self)

source code 

The schema's *id* attribute, defaults to ``None``.

Decorators:
  • @property

version(self)

source code 

The schema's *version* attribute, defaults to ``None``.

Decorators:
  • @property

schema_location(self)

source code 

A list of location hints extracted from the *xsi:schemaLocation* attribute of the schema.

Decorators:
  • @property

no_namespace_schema_location(self)

source code 

A location hint extracted from the *xsi:noNamespaceSchemaLocation* attribute of the schema.

Decorators:
  • @property

default_namespace(self)

source code 

The namespace associated to the empty prefix ''.

Decorators:
  • @property

target_prefix(self)

source code 

The prefix associated to the *targetNamespace*.

Decorators:
  • @property

root_elements(self)

source code 

The list of global elements that are not used by reference in any model of the schema. This is implemented as lazy property because it's computationally expensive to build when the schema model is complex.

Decorators:
  • @property

create_meta_schema(cls, source=None, base_schemas=None, global_maps=None)
Class Method

source code 

Creates a new meta-schema instance.

:param source: an optional argument referencing to or containing the XSD meta-schema resource. Required if the schema class doesn't already have a meta-schema. :param base_schemas: an optional dictionary that contains namespace URIs and schema locations. If provided it's used as substitute for class 's BASE_SCHEMAS. Also a sequence of (namespace, location) items can be provided if there are more schema documents for one or more namespaces. :param global_maps: is an optional argument containing an :class:`XsdGlobals` instance for the new meta schema. If not provided a new map is created.

Decorators:

copy(self)

source code 

Makes a copy of the schema instance. The new instance has independent maps of shared XSD components.

Decorators:
Overrides: xsdbase.XsdValidator.copy

__copy__(self)

source code 

Makes a copy of the schema instance. The new instance has independent maps of shared XSD components.

Decorators:
Overrides: xsdbase.XsdValidator.copy

check_schema(cls, schema, namespaces=None)
Class Method

source code 

Validates the given schema against the XSD meta-schema (:attr:`meta_schema`).

:param schema: the schema instance that has to be validated. :param namespaces: is an optional mapping from namespace prefix to URI.

:raises: :exc:`XMLSchemaValidationError` if the schema is invalid.

Decorators:

built(self)

source code 

Property that is ``True`` if schema validator has been fully parsed and built, ``False`` otherwise.

Decorators:
  • @property
Overrides: xsdbase.XsdValidator.built
(inherited documentation)

validation_attempted(self)

source code 

Property that returns the *validation status* of the XSD validator. It can be 'full', 'partial' or 'none'.

| https://www.w3.org/TR/xmlschema-1/#e-validation_attempted | https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#e-validation_attempted

Decorators:
  • @property
Overrides: xsdbase.XsdValidator.validation_attempted
(inherited documentation)

iter_globals(self, schema=None)

source code 

Creates an iterator for XSD global definitions/declarations related to schema namespace.

:param schema: Optional argument for filtering only globals related to a schema instance.

Decorators:

iter_components(self, xsd_classes=None)

source code 

Creates an iterator for traversing all XSD components of the validator.

:param xsd_classes: returns only a specific class/classes of components, otherwise returns all components.

Decorators:
Overrides: xsdbase.XsdValidator.iter_components
(inherited documentation)

get_converter(self, converter=None, namespaces=None, **kwargs)

source code 

Returns a new converter instance.

:param converter: can be a converter class or instance. If it's an instance the new instance is copied from it and configured with the provided arguments. :param namespaces: is an optional mapping from namespace prefix to URI. :param kwargs: optional arguments for initialize the converter instance. :return: a converter instance.

Decorators:

include_schema(self, location, base_url=None)

source code 

Includes a schema for the same namespace, from a specific URL.

:param location: is the URL of the schema. :param base_url: is an optional base URL for fetching the schema resource. :return: the included :class:`XMLSchema` instance.

Decorators:

import_schema(self, namespace, location, base_url=None, force=False)

source code 

Imports a schema for an external namespace, from a specific URL.

:param namespace: is the URI of the external namespace. :param location: is the URL of the schema. :param base_url: is an optional base URL for fetching the schema resource. :param force: is set to `True` imports the schema also if the namespace is already imported. :return: the imported :class:`XMLSchema` instance.

Decorators:

resolve_qname(self, qname)

source code 

QName resolution for a schema instance.

:param qname: a string in xs:QName format. :returns: an expanded QName in the format "{*namespace-URI*}*local-name*". :raises: `XMLSchemaValueError` for an invalid xs:QName or if the namespace prefix is not declared in the schema instance or if the namespace is not the *targetNamespace* and the namespace is not imported by the schema.

Decorators:

iter_decode(self, source, path=None, validation='lax', process_namespaces=True, namespaces=None, use_defaults=True, decimal_type=None, datetime_types=False, converter=None, defuse=None, timeout=None, **kwargs)

source code 

Creates an iterator for decoding an XML source to a data structure.

:param source: the XML data source. Can be a path to a file or an URI of a resource or an opened file-like object or an Element Tree instance or a string containing XML data. :param path: is an optional XPath expression that matches the parts of the document that have to be decoded. The XPath expression considers the schema as the root element with global elements as its children. :param validation: defines the XSD validation mode to use for decode, can be 'strict', 'lax' or 'skip'. :param process_namespaces: indicates whether to use namespace information in the decoding process, using the map provided with the argument *namespaces* and the map extracted from the XML document. :param namespaces: is an optional mapping from namespace prefix to URI. :param use_defaults: indicates whether to use default values for filling missing data. :param decimal_type: conversion type for `Decimal` objects (generated by XSD `decimal` built-in and derived types), useful if you want to generate a JSON-compatible data structure. :param datetime_types: if set to `True` the datetime and duration XSD types are decoded, otherwise their origin XML string is returned. :param converter: an :class:`XMLSchemaConverter` subclass or instance to use for the decoding. :param defuse: Overrides when to defuse XML data. Can be 'always', 'remote' or 'never'. :param timeout: Overrides the timeout setted for the schema. :param kwargs: Keyword arguments containing options for converter and decoding. :return: Yields a decoded data object, eventually preceded by a sequence of validation or decoding errors.

Decorators:
Overrides: xsdbase.ValidationMixin.iter_decode

iter_encode(self, obj, path=None, validation='lax', namespaces=None, converter=None, **kwargs)

source code 

Creates an iterator for encoding a data structure to an ElementTree's Element.

:param obj: the data that has to be encoded. :param path: is an optional XPath expression for selecting the element of the schema that matches the data that has to be encoded. For default the first global element of the schema is used. :param validation: the XSD validation mode. Can be 'strict', 'lax' or 'skip'. :param namespaces: is an optional mapping from namespace prefix to URI. :param converter: an :class:`XMLSchemaConverter` subclass or instance to use for the encoding. :param kwargs: Keyword arguments containing options for converter and encoding. :return: Yields an Element instance, eventually preceded by a sequence of validation or encoding errors.

Decorators:
Overrides: xsdbase.ValidationMixin.iter_encode

all_errors(self)

source code 

A list with all the building errors of the XSD validator and its components.

Decorators:
  • @property

attrib(self)

source code 

Returns the Element attributes. For compatibility with the ElementTree API.

Decorators:
  • @property

decode(self, source, *args, **kwargs)

source code 

Decodes XML data using the XSD schema/component.

:param source: the source of XML data. For a schema can be a path to a file or an URI of a resource or an opened file-like object or an Element Tree instance or a string containing XML data. For other XSD components can be a string for an attribute or a simple type validators, or an ElementTree's Element otherwise. :param args: arguments that maybe passed to :func:`XMLSchema.iter_decode`. :param kwargs: keyword arguments from the ones included in the optional arguments of the :func:`XMLSchema.iter_decode`. :return: a dictionary like object if the XSD component is an element, a group or a complex type; a list if the XSD component is an attribute group; a simple data type object otherwise. If *validation* argument is 'lax' a 2-items tuple is returned, where the first item is the decoded object and the second item is a list containing the errors. :raises: :exc:`XMLSchemaValidationError` if the object is not decodable by the XSD component, or also if it's invalid when ``validation='strict'`` is provided.

Decorators:

decode_error(self, validation, obj, decoder, reason=None, source=None, namespaces=None, **_kwargs)

source code 

Helper method for generating decode errors. Incompatible with 'skip' validation mode. Il validation mode is 'lax' returns the error, otherwise raises the error.

:param validation: an error-compatible validation mode: can be 'lax' or 'strict'. :param obj: the not validated XML data. :param decoder: the XML data decoder. :param reason: the detailed reason of failed validation. :param source: the XML resource that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. :param _kwargs: keyword arguments of the validation process that are not used.

Decorators:

encode(self, obj, *args, **kwargs)

source code 

Encodes data to XML using the XSD schema/component.

:param obj: the data to be encoded to XML. :param args: arguments that maybe passed to :func:`XMLSchema.iter_encode`. :param kwargs: keyword arguments from the ones included in the optional arguments of the :func:`XMLSchema.iter_encode`. :return: An element tree's Element if the original data is a structured data or a string if it's simple type datum. If *validation* argument is 'lax' a 2-items tuple is returned, where the first item is the encoded object and the second item is a list containing the errors. :raises: :exc:`XMLSchemaValidationError` if the object is not encodable by the XSD component, or also if it's invalid when ``validation='strict'`` is provided.

Decorators:

encode_error(self, validation, obj, encoder, reason=None, source=None, namespaces=None, **_kwargs)

source code 

Helper method for generating encode errors. Incompatible with 'skip' validation mode. Il validation mode is 'lax' returns the error, otherwise raises the error.

:param validation: an error-compatible validation mode: can be 'lax' or 'strict'. :param obj: the not validated XML data. :param encoder: the XML encoder. :param reason: the detailed reason of failed validation. :param source: the XML resource that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. :param _kwargs: keyword arguments of the validation process that are not used.

Decorators:

find(self, path, namespaces=None)

source code 

Finds the first XSD subelement matching the path.

:param path: an XPath expression that considers the XSD component as the root element. :param namespaces: an optional mapping from namespace prefix to full name. :return: The first matching XSD subelement or ``None`` if there is not match.

Decorators:

findall(self, path, namespaces=None)

source code 

Finds all XSD subelements matching the path.

:param path: an XPath expression that considers the XSD component as the root element. :param namespaces: an optional mapping from namespace prefix to full name. :return: a list containing all matching XSD subelements in document order, an empty list is returned if there is no match.

Decorators:

get(self, key, default=None)

source code 

Gets an Element attribute. For compatibility with the ElementTree API.

Decorators:

is_valid(self, source, use_defaults=True)

source code 

Like :meth:`validate` except that do not raises an exception but returns ``True`` if the XML document is valid, ``False`` if it's invalid.

:param source: the source of XML data. For a schema can be a path to a file or an URI of a resource or an opened file-like object or an Element Tree instance or a string containing XML data. For other XSD components can be a string for an attribute or a simple type validators, or an ElementTree's Element otherwise. :param use_defaults: indicates whether to use default values for filling missing data.

Decorators:

iter(self, tag=None)

source code 

Creates an iterator for the XSD element and its subelements. If tag is not `None` or '*', only XSD elements whose matches tag are returned from the iterator. Local elements are expanded without repetitions. Element references are not expanded because the global elements are not descendants of other elements.

Decorators:

iter_errors(self, source, path=None, use_defaults=True, namespaces=None)

source code 

Creates an iterator for the errors generated by the validation of an XML data against the XSD schema/component instance.

:param source: the source of XML data. For a schema can be a path to a file or an URI of a resource or an opened file-like object or an Element Tree instance or a string containing XML data. For other XSD components can be a string for an attribute or a simple type validators, or an ElementTree's Element otherwise. :param path: is an optional XPath expression that defines the parts of the document that have to be validated. The XPath expression considers the schema as the root element with global elements as its children. :param use_defaults: Use schema's default values for filling missing data. :param namespaces: is an optional mapping from namespace prefix to URI.

Decorators:

iterchildren(self, tag=None)

source code 

Creates an iterator for the child elements of the XSD component. If *tag* is not `None` or '*', only XSD elements whose name matches tag are returned from the iterator.

Decorators:

iterfind(self, path, namespaces=None)

source code 

Creates and iterator for all XSD subelements matching the path.

:param path: an XPath expression that considers the XSD component as the root element. :param namespaces: is an optional mapping from namespace prefix to full name. :return: an iterable yielding all matching XSD subelements in document order.

Decorators:

parse_error(self, error, elem=None)

source code 

Helper method for registering parse errors. Does nothing if validation mode is 'skip'. Il validation mode is 'lax' collects the error, otherwise raise the error.

:param error: can be a parse error or an error message. :param elem: the Element instance related to the error, for default uses the 'elem' attribute of the validator, if it's present.

Decorators:

to_dict(self, source, *args, **kwargs)

source code 

Decodes XML data using the XSD schema/component.

:param source: the source of XML data. For a schema can be a path to a file or an URI of a resource or an opened file-like object or an Element Tree instance or a string containing XML data. For other XSD components can be a string for an attribute or a simple type validators, or an ElementTree's Element otherwise. :param args: arguments that maybe passed to :func:`XMLSchema.iter_decode`. :param kwargs: keyword arguments from the ones included in the optional arguments of the :func:`XMLSchema.iter_decode`. :return: a dictionary like object if the XSD component is an element, a group or a complex type; a list if the XSD component is an attribute group; a simple data type object otherwise. If *validation* argument is 'lax' a 2-items tuple is returned, where the first item is the decoded object and the second item is a list containing the errors. :raises: :exc:`XMLSchemaValidationError` if the object is not decodable by the XSD component, or also if it's invalid when ``validation='strict'`` is provided.

Decorators:

to_etree(self, obj, *args, **kwargs)

source code 

Encodes data to XML using the XSD schema/component.

:param obj: the data to be encoded to XML. :param args: arguments that maybe passed to :func:`XMLSchema.iter_encode`. :param kwargs: keyword arguments from the ones included in the optional arguments of the :func:`XMLSchema.iter_encode`. :return: An element tree's Element if the original data is a structured data or a string if it's simple type datum. If *validation* argument is 'lax' a 2-items tuple is returned, where the first item is the encoded object and the second item is a list containing the errors. :raises: :exc:`XMLSchemaValidationError` if the object is not encodable by the XSD component, or also if it's invalid when ``validation='strict'`` is provided.

Decorators:

validate(self, source, use_defaults=True, namespaces=None)

source code 

Validates an XML data against the XSD schema/component instance.

:param source: the source of XML data. For a schema can be a path to a file or an URI of a resource or an opened file-like object or an Element Tree instance or a string containing XML data. For other XSD components can be a string for an attribute or a simple type validators, or an ElementTree's Element otherwise. :param use_defaults: indicates whether to use default values for filling missing data. :param namespaces: is an optional mapping from namespace prefix to URI. :raises: :exc:`XMLSchemaValidationError` if XML *data* instance is not a valid.

Decorators:

validation_error(self, validation, error, obj=None, source=None, namespaces=None, **_kwargs)

source code 

Helper method for generating and updating validation errors. Incompatible with 'skip' validation mode. Il validation mode is 'lax' returns the error, otherwise raises the error.

:param validation: an error-compatible validation mode: can be 'lax' or 'strict'. :param error: an error instance or the detailed reason of failed validation. :param obj: the instance related to the error. :param source: the XML resource related to the validation process. :param namespaces: is an optional mapping from namespace prefix to URI. :param _kwargs: keyword arguments of the validation process that are not used.

Decorators:

validity(self)

source code 

Property that returns the XSD validator's validity. It can be ‘valid’, ‘invalid’ or ‘notKnown’.

| https://www.w3.org/TR/xmlschema-1/#e-validity | https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#e-validity

Decorators:
  • @property