index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
713,412
xmlschema.validators.schemas
validate
Validates an XML data against the XSD schema/component instance. :param source: the source of XML data. Can be an :class:`XMLResource` instance, a path to a file or a URI of a resource or an opened file-like object or an Element instance or an ElementTree instance or a string containing the XML data. :param path: is an optional XPath expression that matches the elements of the XML data that have to be decoded. If not provided the XML root element is selected. :param schema_path: an alternative XPath expression to select the XSD element to use for decoding. Useful if the root of the XML data doesn't match an XSD global element of the schema. :param use_defaults: Use schema's default values for filling missing data. :param namespaces: is an optional mapping from namespace prefix to URI. :param max_depth: maximum level of validation, for default there is no limit. With lazy resources is set to `source.lazy_depth` for managing lazy validation. :param extra_validator: an optional function for performing non-standard validations on XML data. The provided function is called for each traversed element, with the XML element as 1st argument and the corresponding XSD element as 2nd argument. It can be also a generator function and has to raise/yield :exc:`XMLSchemaValidationError` exceptions. :param validation_hook: an optional function for stopping or changing validation at element level. The provided function must accept two arguments, the XML element and the matching XSD element. If the value returned by this function is evaluated to false then the validation process continues without changes, otherwise the validation process is stopped or changed. If the value returned is a validation mode the validation process continues changing the current validation mode to the returned value, otherwise the element and its content are not processed. The function can also stop validation suddenly raising a `XmlSchemaStopValidation` exception. :param allow_empty: for default providing a path argument empty selections of XML data are allowed. Provide `False` to generate a validation error. :param use_location_hints: for default schema locations hints provided within XML data are ignored in order to avoid the change of schema instance. Set this option to `True` to activate dynamic schema loading using schema location hints. :raises: :exc:`XMLSchemaValidationError` if the XML data instance is invalid.
def validate(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NamespacesType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, allow_empty: bool = True, use_location_hints: bool = False) -> None: """ Validates an XML data against the XSD schema/component instance. :param source: the source of XML data. Can be an :class:`XMLResource` instance, a \ path to a file or a URI of a resource or an opened file-like object or an Element \ instance or an ElementTree instance or a string containing the XML data. :param path: is an optional XPath expression that matches the elements of the XML \ data that have to be decoded. If not provided the XML root element is selected. :param schema_path: an alternative XPath expression to select the XSD element \ to use for decoding. Useful if the root of the XML data doesn't match an XSD \ global element of the schema. :param use_defaults: Use schema's default values for filling missing data. :param namespaces: is an optional mapping from namespace prefix to URI. :param max_depth: maximum level of validation, for default there is no limit. \ With lazy resources is set to `source.lazy_depth` for managing lazy validation. :param extra_validator: an optional function for performing non-standard \ validations on XML data. The provided function is called for each traversed \ element, with the XML element as 1st argument and the corresponding XSD \ element as 2nd argument. It can be also a generator function and has to \ raise/yield :exc:`XMLSchemaValidationError` exceptions. :param validation_hook: an optional function for stopping or changing \ validation at element level. The provided function must accept two arguments, \ the XML element and the matching XSD element. If the value returned by this \ function is evaluated to false then the validation process continues without \ changes, otherwise the validation process is stopped or changed. If the value \ returned is a validation mode the validation process continues changing the \ current validation mode to the returned value, otherwise the element and its \ content are not processed. The function can also stop validation suddenly \ raising a `XmlSchemaStopValidation` exception. :param allow_empty: for default providing a path argument empty selections \ of XML data are allowed. Provide `False` to generate a validation error. :param use_location_hints: for default schema locations hints provided within \ XML data are ignored in order to avoid the change of schema instance. Set this \ option to `True` to activate dynamic schema loading using schema location hints. :raises: :exc:`XMLSchemaValidationError` if the XML data instance is invalid. """ for error in self.iter_errors(source, path, schema_path, use_defaults, namespaces, max_depth, extra_validator, validation_hook, allow_empty, use_location_hints, validation='strict'): raise error
(self, source: Union[~T, NoneType, xmlschema.resources.XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[~T] = None, max_depth: Optional[int] = None, extra_validator: Optional[~T] = None, validation_hook: Optional[~T] = None, allow_empty: bool = True, use_location_hints: bool = False) -> NoneType
713,413
xmlschema.validators.xsdbase
validation_error
Helper method for generating and updating validation errors. If validation mode is 'lax' or 'skip' 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 elem: the element related to the error, can be `obj` for elements. :param source: the XML resource or data related to the validation process. :param namespaces: is an optional mapping from namespace prefix to URI. :param kwargs: other keyword arguments of the validation process.
def validation_error(self, validation: str, error: Union[str, Exception], obj: Any = None, elem: Optional[ElementType] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None, **kwargs: Any) -> XMLSchemaValidationError: """ Helper method for generating and updating validation errors. If validation mode is 'lax' or 'skip' 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 elem: the element related to the error, can be `obj` for elements. :param source: the XML resource or data related to the validation process. :param namespaces: is an optional mapping from namespace prefix to URI. :param kwargs: other keyword arguments of the validation process. """ check_validation_mode(validation) if elem is None and is_etree_element(obj): elem = cast(ElementType, obj) if isinstance(error, XMLSchemaValidationError): if error.namespaces is None and namespaces is not None: error.namespaces = namespaces if error.source is None and source is not None: error.source = source if error.obj is None and obj is not None: error.obj = obj elif is_etree_element(error.obj) and elem is not None: if elem.tag == error.obj.tag and elem is not error.obj: error.obj = elem elif isinstance(error, Exception): error = XMLSchemaValidationError(self, obj, str(error), source, namespaces) else: error = XMLSchemaValidationError(self, obj, error, source, namespaces) if error.elem is None and elem is not None: error.elem = elem if validation == 'strict' and error.elem is not None: raise error if error.stack_trace is None and logger.level == logging.DEBUG: error.stack_trace = format_xmlschema_stack() logger.debug("Collect %r with traceback:\n%s", error, error.stack_trace) if 'errors' in kwargs and error not in kwargs['errors']: kwargs['errors'].append(error) return error
(self, validation: str, error: Union[str, Exception], obj: Optional[Any] = None, elem: Optional[~T] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None, **kwargs: Any) -> xmlschema.validators.exceptions.XMLSchemaValidationError
713,414
xmlschema.validators.schemas
version_check
Checks if the element is compatible with the version of the validator and XSD types/facets availability. Invalid vc attributes are not detected in XSD 1.0. :param elem: an Element of the schema. :return: `True` if the schema element is compatible with the validator, `False` otherwise.
def version_check(self, elem: ElementType) -> bool: """ Checks if the element is compatible with the version of the validator and XSD types/facets availability. Invalid vc attributes are not detected in XSD 1.0. :param elem: an Element of the schema. :return: `True` if the schema element is compatible with the validator, \ `False` otherwise. """ if VC_MIN_VERSION in elem.attrib: vc_min_version = elem.attrib[VC_MIN_VERSION] if not XSD_VERSION_PATTERN.match(vc_min_version): if self.XSD_VERSION > '1.0': msg = _("invalid attribute vc:minVersion value") self.parse_error(msg, elem) elif vc_min_version > self.XSD_VERSION: return False if VC_MAX_VERSION in elem.attrib: vc_max_version = elem.attrib[VC_MAX_VERSION] if not XSD_VERSION_PATTERN.match(vc_max_version): if self.XSD_VERSION > '1.0': msg = _("invalid attribute vc:maxVersion value") self.parse_error(msg, elem) elif vc_max_version <= self.XSD_VERSION: return False if VC_TYPE_AVAILABLE in elem.attrib: for qname in elem.attrib[VC_TYPE_AVAILABLE].split(): try: if self.resolve_qname(qname) not in self.maps.types: return False except XMLSchemaNamespaceError: return False except (KeyError, ValueError) as err: self.parse_error(str(err), elem) if VC_TYPE_UNAVAILABLE in elem.attrib: for qname in elem.attrib[VC_TYPE_UNAVAILABLE].split(): try: if self.resolve_qname(qname) not in self.maps.types: break except XMLSchemaNamespaceError: break except (KeyError, ValueError) as err: self.parse_error(err, elem) else: return False if VC_FACET_AVAILABLE in elem.attrib: for qname in elem.attrib[VC_FACET_AVAILABLE].split(): try: facet_name = self.resolve_qname(qname) except XMLSchemaNamespaceError: pass except (KeyError, ValueError) as err: self.parse_error(str(err), elem) else: if self.XSD_VERSION == '1.0': if facet_name not in XSD_10_FACETS: return False elif facet_name not in XSD_11_FACETS: return False if VC_FACET_UNAVAILABLE in elem.attrib: for qname in elem.attrib[VC_FACET_UNAVAILABLE].split(): try: facet_name = self.resolve_qname(qname) except XMLSchemaNamespaceError: break except (KeyError, ValueError) as err: self.parse_error(err, elem) else: if self.XSD_VERSION == '1.0': if facet_name not in XSD_10_FACETS: break elif facet_name not in XSD_11_FACETS: break else: return False return True
(self, elem: Optional[~T]) -> bool
713,480
xmlschema.validators.schemas
XMLSchema11
XSD 1.1 schema class. <schema attributeFormDefault = (qualified | unqualified) : unqualified blockDefault = (#all | List of (extension | restriction | substitution)) : '' defaultAttributes = QName xpathDefaultNamespace = (anyURI | (##defaultNamespace | ##targetNamespace| ##local)) : ##local elementFormDefault = (qualified | unqualified) : unqualified finalDefault = (#all | List of (extension | restriction | list | union)) : '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema namespace . . .}> Content: ((include | import | redefine | override | annotation)*, (defaultOpenContent, annotation*)?, ((simpleType | complexType | group | attributeGroup | element | attribute | notation), annotation*)*) </schema> <schema attributeFormDefault = (qualified | unqualified) : unqualified blockDefault = (#all | List of (extension | restriction | substitution)) : '' elementFormDefault = (qualified | unqualified) : unqualified finalDefault = (#all | List of (extension | restriction | list | union)) : '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema namespace . . .}> Content: ((include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*) </schema>
class XMLSchema11(XMLSchemaBase): """ XSD 1.1 schema class. <schema attributeFormDefault = (qualified | unqualified) : unqualified blockDefault = (#all | List of (extension | restriction | substitution)) : '' defaultAttributes = QName xpathDefaultNamespace = (anyURI | (##defaultNamespace | ##targetNamespace| ##local)) : ##local elementFormDefault = (qualified | unqualified) : unqualified finalDefault = (#all | List of (extension | restriction | list | union)) : '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema namespace . . .}> Content: ((include | import | redefine | override | annotation)*, (defaultOpenContent, annotation*)?, ((simpleType | complexType | group | attributeGroup | element | attribute | notation), annotation*)*) </schema> <schema attributeFormDefault = (qualified | unqualified) : unqualified blockDefault = (#all | List of (extension | restriction | substitution)) : '' elementFormDefault = (qualified | unqualified) : unqualified finalDefault = (#all | List of (extension | restriction | list | union)) : '' id = ID targetNamespace = anyURI version = token xml:lang = language {any attributes with non-schema namespace . . .}> Content: ((include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*) </schema> """ meta_schema: XMLSchemaBase meta_schema = os.path.join(SCHEMAS_DIR, 'XSD_1.1/XMLSchema.xsd') # type: ignore XSD_VERSION = '1.1' BASE_SCHEMAS = { XML_NAMESPACE: os.path.join(SCHEMAS_DIR, 'XML/xml_minimal.xsd'), XSI_NAMESPACE: os.path.join(SCHEMAS_DIR, 'XSI/XMLSchema-instance_minimal.xsd'), XSD_NAMESPACE: os.path.join(SCHEMAS_DIR, 'XSD_1.1/xsd11-extra.xsd'), VC_NAMESPACE: os.path.join(SCHEMAS_DIR, 'VC/XMLSchema-versioning.xsd'), } xsd_complex_type_class = Xsd11ComplexType xsd_attribute_class = Xsd11Attribute xsd_any_attribute_class = Xsd11AnyAttribute xsd_group_class = Xsd11Group xsd_element_class = Xsd11Element xsd_any_class = Xsd11AnyElement xsd_atomic_restriction_class = Xsd11AtomicRestriction xsd_union_class = Xsd11Union xsd_key_class = Xsd11Key xsd_keyref_class = Xsd11Keyref xsd_unique_class = Xsd11Unique
(source: xmlschema.resources.XMLResource, namespace: Optional[str] = None, validation: str = 'strict', global_maps: Optional[xmlschema.validators.global_maps.XsdGlobals] = None, converter: Optional[~T] = None, locations: xmlschema.namespaces.NamespaceResourcesMap = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, uri_mapper: Optional[~T] = None, build: bool = True, use_meta: bool = True, use_fallback: bool = True, use_xpath3: bool = False, loglevel: Union[str, int, NoneType] = None) -> None
713,545
xmlschema.validators.exceptions
XMLSchemaAssertPathWarning
An improper XPath expression found in XSD 1.1 assertion.
class XMLSchemaAssertPathWarning(XMLSchemaWarning): """An improper XPath expression found in XSD 1.1 assertion."""
null
713,546
xmlschema.validators.schemas
XMLSchemaBase
Base class for an XML Schema instance. :param source: a 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 or an :class:`XMLResource` instance. A multi source initialization is supported providing a not empty list of XSD sources. :param namespace: is an optional argument that contains the URI of the namespace that has to used in case the schema has no namespace (chameleon schema). For other cases, when specified, it must be equal to the *targetNamespace* of the schema. :param validation: the XSD validation mode to use for build the schema, that can be 'strict' (default), 'lax' or 'skip'. :param global_maps: is an optional argument containing an :class:`XsdGlobals` instance, a mediator object for sharing declaration data between dependents schema instances. :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. :param locations: schema extra location hints, that can include custom resource locations (e.g. local XSD file instead of remote resource) or additional namespaces to import after processing schema's import statements. Can be a dictionary or a sequence of couples (namespace URI, resource URL). Extra locations passed using a tuple container are not normalized. :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. :param allow: the security mode for accessing resource locations. Can be 'all', 'remote', 'local' or 'sandbox'. Default is 'all' that means all types of URLs are allowed. With 'remote' only remote resource URLs are allowed. With 'local' only file paths and URLs are allowed. With 'sandbox' only file paths and URLs that are under the directory path identified by source or by the *base_url* argument are allowed. :param defuse: defines when to defuse XML data using a `SafeXMLParser`. Can be 'always', 'remote' or 'never'. For default defuses only remote XML data. :param timeout: the timeout in seconds for fetching resources. Default is `300`. :param uri_mapper: an optional URI mapper for using relocated or URN-addressed resources. Can be a dictionary or a function that takes the URI string and returns a URL, or the argument if there is no mapping for it. :param build: defines whether build the schema maps. Default is `True`. :param use_meta: if `True` the schema processor uses the validator meta-schema, otherwise a new 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. :param use_fallback: if `True` the schema processor uses the validator fallback location hints to load well-known namespaces (e.g. xhtml). :param use_xpath3: if `True` an XSD 1.1 schema instance uses the XPath 3 processor for assertions. For default a full XPath 2.0 processor is used for XSD 1.1 assertions. :param loglevel: for setting a different logging level for schema initialization and building. For default is WARNING (30). For INFO level set it with 20, for DEBUG level with 10. The default loglevel is restored after schema building, when exiting the initialization method. :cvar XSD_VERSION: store the XSD version (1.0 or 1.1). :cvar BASE_SCHEMAS: a dictionary from namespace to schema resource for meta-schema bases. :cvar fallback_locations: fallback schema location hints for other standard namespaces. :cvar meta_schema: the XSD meta-schema instance. :cvar attribute_form_default: the schema's *attributeFormDefault* attribute. Default is 'unqualified'. :cvar element_form_default: the schema's *elementFormDefault* attribute. Default is 'unqualified'. :cvar block_default: the schema's *blockDefault* attribute. Default is ''. :cvar final_default: the schema's *finalDefault* attribute. Default is ''. :cvar default_attributes: the XSD 1.1 schema's *defaultAttributes* attribute. Default is ``None``. :cvar xpath_tokens: symbol table for schema bound XPath 2.0 parsers. Initially set to ``None`` it's redefined at instance level with a dictionary at first use of the XPath selector. The parser symbol table is extended with schema types constructors. :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. :ivar maps: XSD global declarations/definitions maps. This is an instance of :class:`XsdGlobals`, that stores the *global_maps* argument or a new object when this argument is not provided. :ivar converter: the default converter used for XML data decoding/encoding. :ivar locations: schema location hints. :ivar namespaces: a dictionary that maps from the prefixes used by the schema into namespace URI. :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. :ivar includes: a dictionary of included schemas, that maps a schema location to an included schema. It also comprehends schemas included by "xs:redefine" or "xs:override" statements. :ivar warnings: warning messages about failure of import and include elements. :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
class XMLSchemaBase(XsdValidator, ElementPathMixin[Union[SchemaType, XsdElement]], metaclass=XMLSchemaMeta): """ Base class for an XML Schema instance. :param source: a 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 \ or an :class:`XMLResource` instance. A multi source initialization is supported \ providing a not empty list of XSD sources. :param namespace: is an optional argument that contains the URI of the namespace \ that has to used in case the schema has no namespace (chameleon schema). For other \ cases, when specified, it must be equal to the *targetNamespace* of the schema. :param validation: the XSD validation mode to use for build the schema, \ that can be 'strict' (default), 'lax' or 'skip'. :param global_maps: is an optional argument containing an :class:`XsdGlobals` \ instance, a mediator object for sharing declaration data between dependents \ schema instances. :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. :param locations: schema extra location hints, that can include custom resource locations \ (e.g. local XSD file instead of remote resource) or additional namespaces to import after \ processing schema's import statements. Can be a dictionary or a sequence of couples \ (namespace URI, resource URL). Extra locations passed using a tuple container are not \ normalized. :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. :param allow: the security mode for accessing resource locations. Can be \ 'all', 'remote', 'local' or 'sandbox'. Default is 'all' that means all types of \ URLs are allowed. With 'remote' only remote resource URLs are allowed. With 'local' \ only file paths and URLs are allowed. With 'sandbox' only file paths and URLs that \ are under the directory path identified by source or by the *base_url* argument \ are allowed. :param defuse: defines when to defuse XML data using a `SafeXMLParser`. Can be \ 'always', 'remote' or 'never'. For default defuses only remote XML data. :param timeout: the timeout in seconds for fetching resources. Default is `300`. :param uri_mapper: an optional URI mapper for using relocated or URN-addressed \ resources. Can be a dictionary or a function that takes the URI string and returns \ a URL, or the argument if there is no mapping for it. :param build: defines whether build the schema maps. Default is `True`. :param use_meta: if `True` the schema processor uses the validator meta-schema, \ otherwise a new 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. :param use_fallback: if `True` the schema processor uses the validator fallback \ location hints to load well-known namespaces (e.g. xhtml). :param use_xpath3: if `True` an XSD 1.1 schema instance uses the XPath 3 processor \ for assertions. For default a full XPath 2.0 processor is used for XSD 1.1 assertions. :param loglevel: for setting a different logging level for schema initialization \ and building. For default is WARNING (30). For INFO level set it with 20, for \ DEBUG level with 10. The default loglevel is restored after schema building, \ when exiting the initialization method. :cvar XSD_VERSION: store the XSD version (1.0 or 1.1). :cvar BASE_SCHEMAS: a dictionary from namespace to schema resource for meta-schema bases. :cvar fallback_locations: fallback schema location hints for other standard namespaces. :cvar meta_schema: the XSD meta-schema instance. :cvar attribute_form_default: the schema's *attributeFormDefault* attribute. \ Default is 'unqualified'. :cvar element_form_default: the schema's *elementFormDefault* attribute. \ Default is 'unqualified'. :cvar block_default: the schema's *blockDefault* attribute. Default is ''. :cvar final_default: the schema's *finalDefault* attribute. Default is ''. :cvar default_attributes: the XSD 1.1 schema's *defaultAttributes* attribute. \ Default is ``None``. :cvar xpath_tokens: symbol table for schema bound XPath 2.0 parsers. Initially set to \ ``None`` it's redefined at instance level with a dictionary at first use of the XPath \ selector. The parser symbol table is extended with schema types constructors. :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. :ivar maps: XSD global declarations/definitions maps. This is an instance of \ :class:`XsdGlobals`, that stores the *global_maps* argument or a new object \ when this argument is not provided. :ivar converter: the default converter used for XML data decoding/encoding. :ivar locations: schema location hints. :ivar namespaces: a dictionary that maps from the prefixes used by the schema \ into namespace URI. :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. :ivar includes: a dictionary of included schemas, that maps a schema location to an \ included schema. It also comprehends schemas included by "xs:redefine" or \ "xs:override" statements. :ivar warnings: warning messages about failure of import and include elements. :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 attributes type annotations source: XMLResource namespaces: NamespacesType converter: Union[ConverterType] locations: NamespaceResourcesMap maps: XsdGlobals imports: Dict[str, Optional[SchemaType]] _import_statements: Set[str] includes: Dict[str, SchemaType] warnings: List[str] notations: NamespaceView[XsdNotation] types: NamespaceView[BaseXsdType] attributes: NamespaceView[XsdAttribute] attribute_groups: NamespaceView[XsdAttributeGroup] groups: NamespaceView[XsdGroup] elements: NamespaceView[XsdElement] substitution_groups: NamespaceView[List[XsdElement]] identities: NamespaceView[XsdIdentity] XSD_VERSION: str = '1.0' meta_schema: Optional['XMLSchemaBase'] = None BASE_SCHEMAS: Dict[str, str] = {} fallback_locations: Dict[str, str] = LOCATION_HINTS.copy() _annotations: Optional[List[XsdAnnotation]] = None _components = None _root_elements: Optional[Set[str]] = None _xpath_node: Optional[SchemaElementNode] # XSD components classes xsd_notation_class = XsdNotation xsd_complex_type_class = XsdComplexType xsd_attribute_class = XsdAttribute xsd_any_attribute_class = XsdAnyAttribute xsd_attribute_group_class = XsdAttributeGroup xsd_group_class = XsdGroup xsd_element_class = XsdElement xsd_any_class = XsdAnyElement xsd_atomic_restriction_class = XsdAtomicRestriction xsd_list_class = XsdList xsd_union_class = XsdUnion xsd_key_class = XsdKey xsd_keyref_class = XsdKeyref xsd_unique_class = XsdUnique # Schema defaults target_namespace = '' attribute_form_default = 'unqualified' element_form_default = 'unqualified' block_default = '' final_default = '' redefine: Optional['XMLSchemaBase'] = None # Additional defaults for XSD 1.1 default_attributes: Optional[Union[str, XsdAttributeGroup]] = None default_open_content = None override: Optional['XMLSchemaBase'] = None use_xpath3: bool = False # Store XPath constructors tokens (for schema and its assertions) xpath_tokens: Optional[Dict[str, Type[XPathToken]]] = None def __init__(self, source: Union[SchemaSourceType, List[SchemaSourceType]], namespace: Optional[str] = None, validation: str = 'strict', global_maps: Optional[XsdGlobals] = None, converter: Optional[ConverterType] = None, locations: Optional[LocationsType] = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, uri_mapper: Optional[UriMapperType] = None, build: bool = True, use_meta: bool = True, use_fallback: bool = True, use_xpath3: bool = False, loglevel: Optional[Union[str, int]] = None) -> None: super().__init__(validation) self.lock = threading.Lock() # Lock for build operations if loglevel is not None: set_logging_level(loglevel) elif build and global_maps is None: logger.setLevel(logging.WARNING) if allow == 'sandbox' and base_url is None and is_local_url(source): # Allow sandbox mode without a base_url using the initial schema URL as base assert isinstance(source, str) base_url = os.path.dirname(normalize_url(source)) other_sources: List[SchemaSourceType] if isinstance(source, list): if not source: raise XMLSchemaValueError(_("no XSD source provided!")) other_sources = source[1:] source = source[0] else: other_sources = [] if isinstance(source, XMLResource): self.source = source else: self.source = XMLResource( source, base_url, allow, defuse, timeout, uri_mapper=uri_mapper ) logger.debug("Read schema from %r", self.source.url or self.source.source) self.imports = {} self._import_statements = set() self.includes = {} self.warnings = [] self.name = self.source.name root = self.source.root # Initialize schema's namespaces, the XML namespace is implicitly declared. self.namespaces = self.source.get_namespaces({'xml': XML_NAMESPACE}) if 'targetNamespace' in root.attrib: self.target_namespace = root.attrib['targetNamespace'].strip() if not self.target_namespace: # https://www.w3.org/TR/2004/REC-xmlschema-1-20041028/structures.html#element-schema msg = _("the attribute 'targetNamespace' cannot be an empty string") self.parse_error(msg, root) elif namespace is not None and self.target_namespace != namespace: msg = _("wrong namespace ({0!r} instead of {1!r}) for XSD resource {2}") self.parse_error(msg.format(self.target_namespace, namespace, self.url), root) if not self.target_namespace and namespace is not None: # Chameleon schema case self.target_namespace = namespace if '' not in self.namespaces: self.namespaces[''] = namespace elif '' not in self.namespaces: # If not declared map the default namespace to no namespace self.namespaces[''] = '' if self.target_namespace == XMLNS_NAMESPACE: # https://www.w3.org/TR/xmlschema11-1/#sec-nss-special msg = _(f"The namespace {XMLNS_NAMESPACE} cannot be used as 'targetNamespace'") raise XMLSchemaValueError(msg) logger.debug("Schema targetNamespace is %r", self.target_namespace) logger.debug("Declared namespaces: %r", self.namespaces) # Parses the schema defaults if 'attributeFormDefault' in root.attrib: self.attribute_form_default = root.attrib['attributeFormDefault'] if 'elementFormDefault' in root.attrib: self.element_form_default = root.attrib['elementFormDefault'] if 'blockDefault' in root.attrib: if self.meta_schema is None: pass # Skip for XSD 1.0 meta-schema that has blockDefault="#all" else: try: self.block_default = get_xsd_derivation_attribute( root, 'blockDefault', XSD_ELEMENT_DERIVATIONS ) except ValueError as err: self.parse_error(err, root) if 'finalDefault' in root.attrib: try: self.final_default = get_xsd_derivation_attribute(root, 'finalDefault') except ValueError as err: self.parse_error(err, root) if converter is None: self.converter = XMLSchemaConverter else: self.converter = self.get_converter(converter) if self.meta_schema is None: self.locations = NamespaceResourcesMap() # Meta-schema maps creation (MetaXMLSchema10/11 classes) self.maps = global_maps or XsdGlobals(self) for child in self.source.root: if child.tag == XSD_OVERRIDE: self.include_schema(child.attrib['schemaLocation'], self.base_url) return # Meta-schemas don't need to be checked and don't process imports # Complete the namespace map with internal declarations, remapping # identical prefixes that refer to different namespaces. self.namespaces = self.source.get_namespaces(self.namespaces, root_only=False) if isinstance(locations, NamespaceResourcesMap): self.locations = locations elif not locations: self.locations = NamespaceResourcesMap() elif isinstance(locations, tuple): self.locations = NamespaceResourcesMap(locations) else: self.locations = NamespaceResourcesMap( normalize_locations(locations, self.base_url) ) if not use_fallback: self.fallback_locations = {} with self.meta_schema.lock: if not self.meta_schema.maps.types: self.meta_schema.maps.build() # Create or set the XSD global maps instance if isinstance(global_maps, XsdGlobals): self.maps = global_maps elif global_maps is not None: raise XMLSchemaTypeError( _("'global_maps' argument must be an %r instance") % XsdGlobals ) elif use_meta and self.target_namespace not in self.meta_schema.maps.namespaces: self.maps = self.meta_schema.maps.copy(self, validation) else: self.maps = XsdGlobals(self, validation) if use_xpath3 and self.XSD_VERSION > '1.0': self.use_xpath3 = True if any(ns == VC_NAMESPACE for ns in self.namespaces.values()): # For XSD 1.1+ apply versioning filter to schema tree. See the paragraph # 4.2.2 of XSD 1.1 (Part 1: Structures) definition for details. # Ref: https://www.w3.org/TR/xmlschema11-1/#cip if prune_etree(root, selector=lambda x: not self.version_check(x)): for k in list(root.attrib): if k not in ('targetNamespace', VC_MIN_VERSION, VC_MAX_VERSION): del root.attrib[k] # Validate the schema document (transforming validation errors to parse errors) if validation != 'skip': for e in self.meta_schema.iter_errors(root, namespaces=self.namespaces): self.parse_error(e.reason or e, elem=e.elem) self._parse_inclusions() self._parse_imports() # Imports by argument (usually from xsi:schemaLocation attribute). for ns in self.locations: if ns not in self.maps.namespaces: self._import_namespace(ns, self.locations[ns]) # XSD 1.1 default declarations (defaultAttributes, defaultOpenContent, # xpathDefaultNamespace) if self.XSD_VERSION > '1.0': self.xpath_default_namespace = self._parse_xpath_default_namespace(root) if 'defaultAttributes' in root.attrib: try: self.default_attributes = self.resolve_qname(root.attrib['defaultAttributes']) except (ValueError, KeyError, RuntimeError) as err: self.parse_error(err, root) for child in root: if child.tag == XSD_DEFAULT_OPEN_CONTENT: self.default_open_content = XsdDefaultOpenContent(child, self) break _source: Union[SchemaSourceType, XMLResource] for _source in other_sources: if isinstance(_source, XMLResource): resource: XMLResource = _source else: resource = XMLResource(_source, base_url, allow, defuse, timeout) if not resource.root.get('targetNamespace') and self.target_namespace: # Adding a chameleon schema: set the namespace with targetNamespace self.add_schema(resource, namespace=self.target_namespace) else: self.add_schema(resource) try: if build: self.maps.build() finally: if loglevel is not None: logger.setLevel(logging.WARNING) # Restore default logging def __getstate__(self) -> Dict[str, Any]: state = self.__dict__.copy() state.pop('lock', None) state.pop('xpath_tokens', None) return state def __setstate__(self, state: Dict[str, Any]) -> None: self.__dict__.update(state) self.lock = threading.Lock() def __repr__(self) -> str: if self.url: return '%s(name=%r, namespace=%r)' % ( self.__class__.__name__, self.name, self.target_namespace ) return '%s(namespace=%r)' % (self.__class__.__name__, self.target_namespace) def __setattr__(self, name: str, value: Any) -> None: if name == 'maps': if self.meta_schema is None and hasattr(self, 'maps'): msg = _("cannot change the global maps instance of a meta-schema") raise XMLSchemaValueError(msg) super().__setattr__(name, value) self.notations = NamespaceView(value.notations, self.target_namespace) self.types = NamespaceView(value.types, self.target_namespace) self.attributes = NamespaceView(value.attributes, self.target_namespace) self.attribute_groups = NamespaceView(value.attribute_groups, self.target_namespace) self.groups = NamespaceView(value.groups, self.target_namespace) self.elements = NamespaceView(value.elements, self.target_namespace) self.substitution_groups = NamespaceView(value.substitution_groups, self.target_namespace) self.identities = NamespaceView(value.identities, self.target_namespace) value.register(self) else: if name == 'validation': check_validation_mode(value) super().__setattr__(name, value) def __iter__(self) -> Iterator[XsdElement]: yield from sorted(self.elements.values(), key=name_attribute) def __reversed__(self) -> Iterator[XsdElement]: yield from sorted(self.elements.values(), key=name_attribute, reverse=True) def __len__(self) -> int: return len(self.elements) @property def xpath_proxy(self) -> XMLSchemaProxy: return XMLSchemaProxy(self) @property def xpath_node(self) -> SchemaElementNode: """Returns an XPath node for processing an XPath expression on the schema instance.""" if self._xpath_node is None: self._xpath_node = build_schema_node_tree(root=self, uri=self.url) return self._xpath_node @property def xsd_version(self) -> str: """Compatibility property that returns the class attribute XSD_VERSION.""" return self.XSD_VERSION # XML resource attributes access @property def root(self) -> ElementType: """Root element of the schema.""" return self.source.root def get_text(self) -> str: """Returns the source text of the XSD schema.""" return self.source.get_text() @property def url(self) -> Optional[str]: """Schema resource URL, is `None` if the schema is built from an Element or a string.""" return self.source.url @property def base_url(self) -> Optional[str]: """The base URL of the source of the schema.""" return self.source.base_url @property def filepath(self) -> Optional[str]: """The filepath if the schema is loaded from a local XSD file, `None` otherwise.""" return self.source.filepath @property def allow(self) -> str: """ The resource access security mode: can be 'all', 'remote', 'local' or 'sandbox'. """ return self.source.allow @property def defuse(self) -> str: """Defines when to defuse XML data: can be 'always', 'remote' or 'never'.""" return self.source.defuse @property def timeout(self) -> int: """Timeout in seconds for fetching resources.""" return self.source.timeout @property def uri_mapper(self) -> Optional[UriMapperType]: """The optional URI mapper argument for relocating addressed resources.""" return self.source.uri_mapper @property def use_meta(self) -> bool: """Returns `True` if the class meta-schema is used.""" return self.meta_schema is self.__class__.meta_schema # Schema root attributes @property def tag(self) -> str: """Schema root tag. For compatibility with the ElementTree API.""" return self.source.root.tag @property def id(self) -> Optional[str]: """The schema's *id* attribute, defaults to ``None``.""" return self.source.root.get('id') @property def version(self) -> Optional[str]: """The schema's *version* attribute, defaults to ``None``.""" return self.source.root.get('version') @property def schema_location(self) -> List[Tuple[str, str]]: """ A list of location hints extracted from the *xsi:schemaLocation* attribute of the schema. """ return [(k, v) for k, v in self.source.iter_location_hints() if k] @property def no_namespace_schema_location(self) -> Optional[str]: """ A location hint extracted from the *xsi:noNamespaceSchemaLocation* attribute of the schema. """ for k, v in self.source.iter_location_hints(): if not k: return v return None @property def default_namespace(self) -> Optional[str]: """The namespace associated to the empty prefix ''.""" return self.namespaces.get('') @property def target_prefix(self) -> str: """The prefix associated to the *targetNamespace*.""" for prefix, namespace in self.namespaces.items(): if namespace == self.target_namespace: return prefix return '' @classmethod def builtin_types(cls) -> NamespaceView[BaseXsdType]: """Returns the XSD built-in types of the meta-schema.""" if cls.meta_schema is None: raise XMLSchemaRuntimeError(_("meta-schema unavailable for %r") % cls) try: meta_schema: SchemaType = cls.meta_schema.maps.namespaces[XSD_NAMESPACE][0] builtin_types = meta_schema.types except KeyError: raise XMLSchemaNotBuiltError( cls.meta_schema, _("missing XSD namespace in meta-schema") ) else: if not builtin_types: cls.meta_schema.build() return builtin_types @property def annotations(self) -> List[XsdAnnotation]: """ Annotations related to schema object. This list includes the annotations of xs:include, xs:import, xs:redefine and xs:override elements. """ if self._annotations is None: self._annotations = [] for elem in self.source.root: if elem.tag == XSD_ANNOTATION: self._annotations.append(XsdAnnotation(elem, self)) elif elem.tag in (XSD_IMPORT, XSD_INCLUDE, XSD_DEFAULT_OPEN_CONTENT): child = get_xsd_annotation_child(elem) if child is not None: annotation = XsdAnnotation(child, self, parent_elem=elem) self._annotations.append(annotation) elif elem.tag in (XSD_REDEFINE, XSD_OVERRIDE): for child in elem: if child.tag == XSD_ANNOTATION: annotation = XsdAnnotation(child, self, parent_elem=elem) self._annotations.append(annotation) return self._annotations @property def components(self) -> Dict[ElementType, XsdComponent]: """A map from XSD ElementTree elements to their schema components.""" if self._components is None: self.check_validator(self.validation) self._components = { c.elem: c for c in self.iter_components() if isinstance(c, XsdComponent) } return self._components @property def root_elements(self) -> List[XsdElement]: """ 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. """ if not self.elements: return [] elif len(self.elements) == 1: return list(self.elements.values()) elif self._root_elements is None: names = {e.name for e in self.elements.values()} for xsd_element in self.elements.values(): for e in xsd_element.iter(): if e is xsd_element or isinstance(e, XsdAnyElement): continue elif e.ref or e.parent is None: if e.name in names: names.discard(e.name) if not names: break self._root_elements = set(names) assert self._root_elements is not None return [e for e in self.elements.values() if e.name in self._root_elements] @property def simple_types(self) -> List[XsdSimpleType]: """Returns a list containing the global simple types.""" return [x for x in self.types.values() if isinstance(x, XsdSimpleType)] @property def complex_types(self) -> List[XsdComplexType]: """Returns a list containing the global complex types.""" return [x for x in self.types.values() if isinstance(x, XsdComplexType)] @classmethod def create_meta_schema(cls, source: Optional[str] = None, base_schemas: Union[None, Dict[str, str], List[Tuple[str, str]]] = None, global_maps: Optional[XsdGlobals] = None) -> SchemaType: """ 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 is used as substitute for class 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. """ if source is None: if cls.meta_schema is None or not cls.meta_schema.url: raise XMLSchemaValueError(_("Missing meta-schema source URL")) source = cls.meta_schema.url _base_schemas: Union[ItemsView[str, str], List[Tuple[str, str]]] if base_schemas is None: _base_schemas = cls.BASE_SCHEMAS.items() elif isinstance(base_schemas, dict): _base_schemas = base_schemas.items() else: try: _base_schemas = [(n, l) for n, l in base_schemas] except ValueError: msg = _("The argument 'base_schemas' must be a " "dictionary or a sequence of couples") raise XMLSchemaValueError(msg) from None meta_schema: SchemaType meta_schema_class = cls if cls.meta_schema is None else cls.meta_schema.__class__ if global_maps is None: meta_schema = meta_schema_class(source, XSD_NAMESPACE, defuse='never', build=False) global_maps = meta_schema.maps elif XSD_NAMESPACE not in global_maps.namespaces: meta_schema = meta_schema_class(source, XSD_NAMESPACE, global_maps=global_maps, defuse='never', build=False) else: meta_schema = global_maps.namespaces[XSD_NAMESPACE][0] for ns, location in _base_schemas: if ns == XSD_NAMESPACE: meta_schema.include_schema(location=location) elif ns not in global_maps.namespaces: meta_schema.import_schema(namespace=ns, location=location) return meta_schema def simple_type_factory(self, elem: ElementType, schema: Optional[SchemaType] = None, parent: Optional[XsdComponent] = None) -> XsdSimpleType: """ Factory function for XSD simple types. Parses the xs:simpleType element and its child component, that can be a restriction, a list or a union. Annotations are linked to simple type instance, omitting the inner annotation if both are given. """ if schema is None: schema = self annotation = None try: child = elem[0] except IndexError: return cast(XsdSimpleType, self.maps.types[XSD_ANY_SIMPLE_TYPE]) else: if child.tag == XSD_ANNOTATION: annotation = XsdAnnotation(child, schema, parent) try: child = elem[1] except IndexError: msg = _("(restriction | list | union) expected") schema.parse_error(msg, elem) return cast(XsdSimpleType, self.maps.types[XSD_ANY_SIMPLE_TYPE]) xsd_type: XsdSimpleType if child.tag == XSD_RESTRICTION: xsd_type = self.xsd_atomic_restriction_class(child, schema, parent) elif child.tag == XSD_LIST: xsd_type = self.xsd_list_class(child, schema, parent) elif child.tag == XSD_UNION: xsd_type = self.xsd_union_class(child, schema, parent) else: msg = _("(restriction | list | union) expected") schema.parse_error(msg, elem) return cast(XsdSimpleType, self.maps.types[XSD_ANY_SIMPLE_TYPE]) if annotation is not None: xsd_type._annotation = annotation try: xsd_type.name = get_qname(schema.target_namespace, elem.attrib['name']) except KeyError: if parent is None: msg = _("missing attribute 'name' in a global simpleType") schema.parse_error(msg, elem) xsd_type.name = 'nameless_%s' % str(id(xsd_type)) else: if parent is not None: msg = _("attribute 'name' not allowed for a local simpleType") schema.parse_error(msg, elem) xsd_type.name = None if 'final' in elem.attrib: try: xsd_type._final = get_xsd_derivation_attribute(elem, 'final') except ValueError as err: xsd_type.parse_error(err, elem) return xsd_type def create_any_content_group(self, parent: Union[XsdComplexType, XsdGroup], any_element: Optional[XsdAnyElement] = None) -> XsdGroup: """ Creates a model group related to schema instance that accepts any content. :param parent: the parent component to set for the content group. :param any_element: an optional any element to use for the content group. \ When provided it's copied, linked to the group and the minOccurs/maxOccurs \ are set to 0 and 'unbounded'. """ group: XsdGroup = self.xsd_group_class(SEQUENCE_ELEMENT, self, parent) if isinstance(any_element, XsdAnyElement): particle = _copy(any_element) particle.min_occurs = 0 particle.max_occurs = None particle.parent = group group.append(particle) else: group.append(self.xsd_any_class(ANY_ELEMENT, self, group)) return group def create_empty_content_group(self, parent: Union[XsdComplexType, XsdGroup], model: str = 'sequence', **attrib: Any) -> XsdGroup: if model == 'sequence': group_elem = Element(XSD_SEQUENCE, **attrib) elif model == 'choice': group_elem = Element(XSD_CHOICE, **attrib) elif model == 'all': group_elem = Element(XSD_ALL, **attrib) else: msg = _("'model' argument must be (sequence | choice | all)") raise XMLSchemaValueError(msg) group_elem.text = '\n ' return self.xsd_group_class(group_elem, self, parent) def create_any_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \ -> XsdAttributeGroup: """ Creates an attribute group related to schema instance that accepts any attribute. :param parent: the parent component to set for the attribute group. """ attribute_group = self.xsd_attribute_group_class( ATTRIBUTE_GROUP_ELEMENT, self, parent ) attribute_group[None] = self.xsd_any_attribute_class( ANY_ATTRIBUTE_ELEMENT, self, attribute_group ) return attribute_group def create_empty_attribute_group(self, parent: Union[XsdComplexType, XsdElement]) \ -> XsdAttributeGroup: """ Creates an empty attribute group related to schema instance. :param parent: the parent component to set for the attribute group. """ return self.xsd_attribute_group_class(ATTRIBUTE_GROUP_ELEMENT, self, parent) def create_any_type(self) -> XsdComplexType: """ Creates a xs:anyType equivalent type related with the wildcards connected to global maps of the schema instance in order to do a correct namespace lookup during wildcards validation. """ schema = self.meta_schema or self any_type = self.xsd_complex_type_class( elem=Element(XSD_COMPLEX_TYPE, name=XSD_ANY_TYPE), schema=schema, parent=None, mixed=True, block='', final='' ) assert isinstance(any_type.content, XsdGroup) any_type.content.append(self.xsd_any_class( ANY_ELEMENT, schema, any_type.content )) any_type.attributes[None] = self.xsd_any_attribute_class( ANY_ATTRIBUTE_ELEMENT, schema, any_type.attributes ) any_type.maps = any_type.content.maps = any_type.content[0].maps = \ any_type.attributes[None].maps = self.maps return any_type def create_element(self, name: str, parent: Optional[XsdComponent] = None, text: Optional[str] = None, **attrib: Any) -> XsdElement: """ Creates a xs:element instance related to schema component. Used as dummy element for validation/decoding/encoding operations of wildcards and complex types. """ elem = Element(XSD_ELEMENT, name=name, **attrib) if text is not None: elem.text = text return self.xsd_element_class(elem=elem, schema=self, parent=parent) def copy(self) -> SchemaType: """ Makes a copy of the schema instance. The new instance has independent maps of shared XSD components. """ schema: SchemaType = object.__new__(self.__class__) schema.__dict__.update(self.__dict__) schema.source = _copy(self.source) schema.errors = self.errors[:] schema.warnings = self.warnings[:] schema.namespaces = dict(self.namespaces) schema.locations = NamespaceResourcesMap(self.locations) schema.imports = self.imports.copy() schema.includes = self.includes.copy() schema.maps = self.maps.copy(validator=schema) return schema __copy__ = copy def check_validator(self, validation: str = 'strict') -> None: """Checks the status of a schema validator against a validation mode.""" check_validation_mode(validation) if self.built: pass elif self.meta_schema is None: self.build() # Meta-schema lazy build elif validation == 'skip' and self.validation == 'skip' and \ any(isinstance(comp, tuple) or comp.validation_attempted == 'partial' for comp in self.iter_globals()): pass else: raise XMLSchemaNotBuiltError(self, _("schema %r is not built") % self) def build(self) -> None: """Builds the schema's XSD global maps.""" self.maps.build() def clear(self) -> None: """Clears the schema's XSD global maps.""" self.maps.clear() self._xpath_node = None self._annotations = None self._components = None self._root_elements = None @property def built(self) -> bool: if any(not isinstance(g, XsdComponent) or not g.built for g in self.iter_globals()): return False for _xsd_global in self.iter_globals(): return True if self.meta_schema is None: return False # No XSD globals: check with a lookup of schema child elements. prefix = f'{{{self.target_namespace}}}' if self.target_namespace else '' for child in self.source.root: if child.tag in {XSD_REDEFINE, XSD_OVERRIDE}: for e in filter(lambda x: x.tag in GLOBAL_TAGS, child): name = e.get('name') if name is not None: try: if not self.maps.lookup(e.tag, prefix + name if prefix else name).built: return False except KeyError: return False elif child.tag in GLOBAL_TAGS: name = child.get('name') if name is not None: try: if not self.maps.lookup(child.tag, prefix + name if prefix else name).built: return False except KeyError: return False return True @property def validation_attempted(self) -> str: if self.built: return 'full' elif any(isinstance(comp, tuple) or comp.validation_attempted == 'partial' for comp in self.iter_globals()): return 'partial' else: return 'none' def iter_globals(self, schema: Optional[SchemaType] = None) \ -> Iterator[Union[SchemaGlobalType, Tuple[Any, ...]]]: """ 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. """ if schema is None: yield from self.notations.values() yield from self.types.values() yield from self.attributes.values() yield from self.attribute_groups.values() yield from self.groups.values() yield from self.elements.values() else: def schema_filter(x: Union[XsdComponent, Tuple[ElementType, SchemaType]]) -> bool: if isinstance(x, tuple): return x[1] is schema return x.schema is schema yield from filter(schema_filter, self.notations.values()) yield from filter(schema_filter, self.types.values()) yield from filter(schema_filter, self.attributes.values()) yield from filter(schema_filter, self.attribute_groups.values()) yield from filter(schema_filter, self.groups.values()) yield from filter(schema_filter, self.elements.values()) def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[Union[XsdComponent, SchemaType]]: """ Iterates yielding the schema and its components. For default includes all the relevant components of the schema, excluding only facets and empty attribute groups. The first returned component is the schema itself. :param xsd_classes: provide a class or a tuple of classes to \ restrict the range of component types yielded. """ if xsd_classes is None or isinstance(self, xsd_classes): yield self for xsd_global in self.iter_globals(self): if not isinstance(xsd_global, tuple): yield from xsd_global.iter_components(xsd_classes) def get_schema(self, namespace: str) -> SchemaType: """ Returns the first schema loaded for a namespace. Raises a `KeyError` if the requested namespace is not loaded. """ try: return cast(SchemaType, self.maps.namespaces[namespace][0]) except KeyError: if not namespace: return self msg = _('the namespace {!r} is not loaded') raise XMLSchemaKeyError(msg.format(namespace)) from None def get_converter(self, converter: Optional[ConverterType] = None, **kwargs: Any) -> XMLSchemaConverter: """ 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 kwargs: optional arguments for initialize the converter instance. :return: a converter instance. """ if converter is None: converter = self.converter if isinstance(converter, XMLSchemaConverter): return converter.copy(keep_namespaces=False, **kwargs) elif issubclass(converter, XMLSchemaConverter): # noinspection PyCallingNonCallable return converter(**kwargs) else: msg = _("'converter' argument must be a {0!r} subclass or instance: {1!r}") raise XMLSchemaTypeError(msg.format(XMLSchemaConverter, converter)) def get_locations(self, namespace: str) -> List[str]: """Get a list of location hints for a namespace.""" try: return list(self.locations[namespace]) except KeyError: return [] def get_element(self, tag: str, path: Optional[str] = None, namespaces: Optional[NamespacesType] = None) -> Optional[XsdElement]: if not path: xsd_element = self.find(tag) return xsd_element if isinstance(xsd_element, XsdElement) else None elif path[-1] == '*': xsd_element = self.find(path[:-1] + tag, namespaces) if isinstance(xsd_element, XsdElement): return xsd_element obj = self.maps.elements.get(tag) return obj if isinstance(obj, XsdElement) else None else: xsd_element = self.find(path, namespaces) return xsd_element if isinstance(xsd_element, XsdElement) else None def create_bindings(self, *bases: type, **attrs: Any) -> None: """ Creates data object bindings for XSD elements of the schema. :param bases: base classes to use for creating the binding classes. :param attrs: attribute and method definitions for the binding classes body. """ for xsd_component in self.iter_components(): if isinstance(xsd_component, XsdElement): xsd_component.get_binding(*bases, replace_existing=True, **attrs) def _parse_inclusions(self) -> None: """Processes schema document inclusions and redefinitions/overrides.""" for child in self.source.root: if 'schemaLocation' not in child.attrib: continue location = child.attrib['schemaLocation'].strip() if child.tag == XSD_INCLUDE: try: logger.info("Include schema from %r", location) self.include_schema(location, self.base_url) except OSError as err: # It is not an error if the location fail to resolve: # https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#compound-schema # https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#src-include self.warnings.append("Include schema failed: %s." % str(err)) warnings.warn(self.warnings[-1], XMLSchemaIncludeWarning, stacklevel=3) except (XMLSchemaParseError, XMLSchemaTypeError, ParseError) as err: msg = _('cannot include schema {0!r}: {1}') if isinstance(err, (XMLSchemaParseError, ParseError)): self.parse_error(msg.format(location, err), child) else: raise type(err)(msg.format(location, err)) elif child.tag == XSD_REDEFINE: try: logger.info("Redefine schema %r", location) schema = self.include_schema(location, self.base_url) except OSError as err: # If the xs:redefine doesn't contain components (annotation excluded) # the statement is equivalent to an include, so no error is generated, # otherwise fails. self.warnings.append(_("Redefine schema failed: %s") % str(err)) warnings.warn(self.warnings[-1], XMLSchemaIncludeWarning, stacklevel=3) if any(e.tag != XSD_ANNOTATION and not callable(e.tag) for e in child): self.parse_error(err, child) except (XMLSchemaParseError, XMLSchemaTypeError, ParseError) as err: msg = _('cannot redefine schema {0!r}: {1}') if isinstance(err, (XMLSchemaParseError, ParseError)): self.parse_error(msg.format(location, err), child) else: raise type(err)(msg.format(location, err)) else: schema.redefine = self elif child.tag == XSD_OVERRIDE and self.XSD_VERSION != '1.0': try: logger.info("Override schema %r", location) schema = self.include_schema(location, self.base_url) except OSError as err: # If the override doesn't contain components (annotation excluded) # the statement is equivalent to an include, so no error is generated, # otherwise fails. self.warnings.append(_("Override schema failed: %s") % str(err)) warnings.warn(self.warnings[-1], XMLSchemaIncludeWarning, stacklevel=3) if any(e.tag != XSD_ANNOTATION and not callable(e.tag) for e in child): self.parse_error(str(err), child) else: schema.override = self def include_schema(self, location: str, base_url: Optional[str] = None, build: bool = False) -> SchemaType: """ 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. :param build: defines when to build the imported schema, the default is to not build. :return: the included :class:`XMLSchema` instance. """ schema: SchemaType url = normalize_url(location, base_url) for schema in self.maps.namespaces[self.target_namespace]: if url == schema.url: logger.info("Resource %r is already loaded", location) break else: schema = type(self)( source=url, namespace=self.target_namespace, validation=self.validation, global_maps=self.maps, converter=self.converter, locations=self.locations, base_url=self.base_url, allow=self.allow, defuse=self.defuse, timeout=self.timeout, uri_mapper=self.uri_mapper, build=build, use_xpath3=self.use_xpath3, ) if schema is self: return self elif location not in self.includes: self.includes[location] = schema elif self.includes[location] is not schema: self.includes[url] = schema return schema def _parse_imports(self) -> None: """ Parse namespace import elements. Imports are done on namespace basis, not on single resource. A warning is generated for a failure of a namespace import. """ namespace_imports = NamespaceResourcesMap(map( lambda x: (x.get('namespace'), x.get('schemaLocation')), filter(lambda x: x.tag == XSD_IMPORT, self.source.root) )) for namespace, locations in namespace_imports.items(): # Checks the namespace against the targetNamespace of the schema if namespace is None: namespace = '' if namespace == self.target_namespace: msg = _("if the 'namespace' attribute is not present on " "the import statement then the imported schema " "must have a 'targetNamespace'") self.parse_error(msg) continue elif namespace == self.target_namespace: msg = _("the attribute 'namespace' must be different " "from schema's 'targetNamespace'") self.parse_error(msg) continue # Register if the namespace has a xs:import statement self._import_statements.add(namespace) # Skip import of already imported namespaces if self.imports.get(namespace) is not None: continue elif namespace in self.maps.namespaces: self.imports[namespace] = self.maps.namespaces[namespace][0] continue locations = [url for url in locations if url] if not namespace: pass elif not locations: locations = self.get_locations(namespace) elif all(is_remote_url(url) for url in locations): # If all import schema locations are remote URLs and there are local hints # that match a local file path, try the local hints before schema locations. # This is not the standard processing for XSD imports, but resolve the problem # of local processing of schemas tested to work from a http server, providing # explicit local hints. local_hints = [url for url in self.get_locations(namespace) if url and url_path_is_file(url)] if local_hints: locations = local_hints + locations if namespace in self.fallback_locations: locations.append(self.fallback_locations[namespace]) self._import_namespace(namespace, locations) def _import_namespace(self, namespace: str, locations: List[str]) -> None: import_error: Optional[Exception] = None for url in locations: try: logger.debug("Import namespace %r from %r", namespace, url) self.import_schema(namespace, url, self.base_url) except OSError as err: # It's not an error if the location access fails (ref. section 4.2.6.2): # https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#composition-schemaImport logger.debug('%s', err) if import_error is None: import_error = err except (XMLSchemaParseError, XMLSchemaTypeError, ParseError) as err: if is_defuse_error(err): # Consider defuse of XML data as a location access fail logger.debug('%s', err) if import_error is None: import_error = err else: if namespace: msg = _("cannot import namespace {0!r}: {1}").format(namespace, err) else: msg = _("cannot import chameleon schema: %s") % err if isinstance(err, (XMLSchemaParseError, ParseError)): self.parse_error(msg) else: raise type(err)(msg) except XMLSchemaValueError as err: self.parse_error(err) else: logger.info("Namespace %r imported from %r", namespace, url) break else: if import_error is not None: msg = "Import of namespace {!r} from {!r} failed: {}." self.warnings.append(msg.format(namespace, locations, str(import_error))) warnings.warn(self.warnings[-1], XMLSchemaImportWarning, stacklevel=4) self.imports[namespace] = None def import_schema(self, namespace: str, location: str, base_url: Optional[str] = None, force: bool = False, build: bool = False) -> Optional[SchemaType]: """ 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: if set to `True` imports the schema also if the namespace is already imported. :param build: defines when to build the imported schema, the default is to not build. :return: the imported :class:`XMLSchema` instance. """ if location == self.url: return self if not force: if self.imports.get(namespace) is not None: return self.imports[namespace] elif namespace in self.maps.namespaces: self.imports[namespace] = self.maps.namespaces[namespace][0] return self.imports[namespace] schema: SchemaType url = normalize_url(location, base_url) imported_ns = self.imports.get(namespace) if imported_ns is not None and imported_ns.url == url: return imported_ns elif namespace in self.maps.namespaces: for schema in self.maps.namespaces[namespace]: if url == schema.url: self.imports[namespace] = schema return schema locations = deepcopy(self.locations) if namespace in locations: locations.pop(namespace) schema = type(self)( source=url, validation=self.validation, global_maps=self.maps, converter=self.converter, locations=locations, base_url=self.base_url, allow=self.allow, defuse=self.defuse, timeout=self.timeout, uri_mapper=self.uri_mapper, build=build, use_xpath3=self.use_xpath3, ) if schema.target_namespace != namespace: msg = _('imported schema {0!r} has an unmatched namespace {1!r}') raise XMLSchemaValueError(msg.format(location, namespace)) self.imports[namespace] = schema return schema def add_schema(self, source: SchemaSourceType, namespace: Optional[str] = None, build: bool = False) -> SchemaType: """ Add another schema source to the maps of the instance. :param source: a 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. :param namespace: is an optional argument that contains the URI of the namespace \ that has to used in case the schema has no namespace (chameleon schema). For other \ cases, when specified, it must be equal to the *targetNamespace* of the schema. :param build: defines when to build the imported schema, the default is to not build. :return: the added :class:`XMLSchema` instance. """ locations = deepcopy(self.locations) if namespace is None: if '' in locations: locations.pop('') elif namespace in locations: locations.pop(namespace) return type(self)( source=source, namespace=namespace, validation=self.validation, global_maps=self.maps, converter=self.converter, locations=locations, base_url=self.base_url, allow=self.allow, defuse=self.defuse, timeout=self.timeout, uri_mapper=self.uri_mapper, build=build, use_xpath3=self.use_xpath3, ) def export(self, target: Union[str, Path], save_remote: bool = False, remove_residuals: bool = True, exclude_locations: Optional[List[str]] = None, loglevel: Optional[Union[str, int]] = None) -> Dict[str, str]: """ Exports a schema instance. The schema instance is exported to a directory with also the hierarchy of imported/included schemas. :param target: a path to a local empty directory. :param save_remote: if `True` is provided saves also remote schemas. :param remove_residuals: for default removes residual remote schema \ locations from redundant import statements. :param exclude_locations: explicitly exclude schema locations from \ substitution or removal. :param loglevel: for setting a different logging level for schema export. :return: a dictionary containing the map of modified locations. """ return export_schema( schema=self, target=target, save_remote=save_remote, remove_residuals=remove_residuals, exclude_locations=exclude_locations, loglevel=loglevel ) def version_check(self, elem: ElementType) -> bool: """ Checks if the element is compatible with the version of the validator and XSD types/facets availability. Invalid vc attributes are not detected in XSD 1.0. :param elem: an Element of the schema. :return: `True` if the schema element is compatible with the validator, \ `False` otherwise. """ if VC_MIN_VERSION in elem.attrib: vc_min_version = elem.attrib[VC_MIN_VERSION] if not XSD_VERSION_PATTERN.match(vc_min_version): if self.XSD_VERSION > '1.0': msg = _("invalid attribute vc:minVersion value") self.parse_error(msg, elem) elif vc_min_version > self.XSD_VERSION: return False if VC_MAX_VERSION in elem.attrib: vc_max_version = elem.attrib[VC_MAX_VERSION] if not XSD_VERSION_PATTERN.match(vc_max_version): if self.XSD_VERSION > '1.0': msg = _("invalid attribute vc:maxVersion value") self.parse_error(msg, elem) elif vc_max_version <= self.XSD_VERSION: return False if VC_TYPE_AVAILABLE in elem.attrib: for qname in elem.attrib[VC_TYPE_AVAILABLE].split(): try: if self.resolve_qname(qname) not in self.maps.types: return False except XMLSchemaNamespaceError: return False except (KeyError, ValueError) as err: self.parse_error(str(err), elem) if VC_TYPE_UNAVAILABLE in elem.attrib: for qname in elem.attrib[VC_TYPE_UNAVAILABLE].split(): try: if self.resolve_qname(qname) not in self.maps.types: break except XMLSchemaNamespaceError: break except (KeyError, ValueError) as err: self.parse_error(err, elem) else: return False if VC_FACET_AVAILABLE in elem.attrib: for qname in elem.attrib[VC_FACET_AVAILABLE].split(): try: facet_name = self.resolve_qname(qname) except XMLSchemaNamespaceError: pass except (KeyError, ValueError) as err: self.parse_error(str(err), elem) else: if self.XSD_VERSION == '1.0': if facet_name not in XSD_10_FACETS: return False elif facet_name not in XSD_11_FACETS: return False if VC_FACET_UNAVAILABLE in elem.attrib: for qname in elem.attrib[VC_FACET_UNAVAILABLE].split(): try: facet_name = self.resolve_qname(qname) except XMLSchemaNamespaceError: break except (KeyError, ValueError) as err: self.parse_error(err, elem) else: if self.XSD_VERSION == '1.0': if facet_name not in XSD_10_FACETS: break elif facet_name not in XSD_11_FACETS: break else: return False return True def resolve_qname(self, qname: str, namespace_imported: bool = True) -> str: """ QName resolution for a schema instance. :param qname: a string in xs:QName format. :param namespace_imported: if this argument is `True` raises an \ `XMLSchemaNamespaceError` if the namespace of the QName is not the \ *targetNamespace* and the namespace is not imported by the schema. :returns: an expanded QName in the format "{*namespace-URI*}*local-name*". :raises: `XMLSchemaValueError` for an invalid xs:QName is found, \ `XMLSchemaKeyError` if the namespace prefix is not declared in the \ schema instance. """ qname = qname.strip() if not qname or ' ' in qname or '\t' in qname or '\n' in qname: msg = _("{!r} is not a valid value for xs:QName") raise XMLSchemaValueError(msg.format(qname)) if qname[0] == '{': try: namespace, local_name = qname[1:].split('}') except ValueError: msg = _("{!r} is not a valid value for xs:QName") raise XMLSchemaValueError(msg.format(qname)) elif ':' in qname: try: prefix, local_name = qname.split(':') except ValueError: msg = _("{!r} is not a valid value for xs:QName") raise XMLSchemaValueError(msg.format(qname)) else: try: namespace = self.namespaces[prefix] except KeyError: msg = _("prefix {!r} not found in namespace map") raise XMLSchemaKeyError(msg.format(prefix)) else: namespace, local_name = self.namespaces.get('', ''), qname if not namespace: if namespace_imported and self.target_namespace \ and '' not in self._import_statements: msg = _("the QName {!r} is mapped to no namespace, but this requires " "that there is an xs:import statement in the schema without " "the 'namespace' attribute.") raise XMLSchemaNamespaceError(msg.format(qname)) return local_name elif namespace_imported and self.meta_schema is not None and \ namespace != self.target_namespace and \ namespace not in {XSD_NAMESPACE, XSI_NAMESPACE} and \ namespace not in self._import_statements: msg = _("the QName {0!r} is mapped to the namespace {1!r}, but this " "namespace has not an xs:import statement in the schema.") raise XMLSchemaNamespaceError(msg.format(qname, namespace)) return f'{{{namespace}}}{local_name}' def validate(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NamespacesType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, allow_empty: bool = True, use_location_hints: bool = False) -> None: """ Validates an XML data against the XSD schema/component instance. :param source: the source of XML data. Can be an :class:`XMLResource` instance, a \ path to a file or a URI of a resource or an opened file-like object or an Element \ instance or an ElementTree instance or a string containing the XML data. :param path: is an optional XPath expression that matches the elements of the XML \ data that have to be decoded. If not provided the XML root element is selected. :param schema_path: an alternative XPath expression to select the XSD element \ to use for decoding. Useful if the root of the XML data doesn't match an XSD \ global element of the schema. :param use_defaults: Use schema's default values for filling missing data. :param namespaces: is an optional mapping from namespace prefix to URI. :param max_depth: maximum level of validation, for default there is no limit. \ With lazy resources is set to `source.lazy_depth` for managing lazy validation. :param extra_validator: an optional function for performing non-standard \ validations on XML data. The provided function is called for each traversed \ element, with the XML element as 1st argument and the corresponding XSD \ element as 2nd argument. It can be also a generator function and has to \ raise/yield :exc:`XMLSchemaValidationError` exceptions. :param validation_hook: an optional function for stopping or changing \ validation at element level. The provided function must accept two arguments, \ the XML element and the matching XSD element. If the value returned by this \ function is evaluated to false then the validation process continues without \ changes, otherwise the validation process is stopped or changed. If the value \ returned is a validation mode the validation process continues changing the \ current validation mode to the returned value, otherwise the element and its \ content are not processed. The function can also stop validation suddenly \ raising a `XmlSchemaStopValidation` exception. :param allow_empty: for default providing a path argument empty selections \ of XML data are allowed. Provide `False` to generate a validation error. :param use_location_hints: for default schema locations hints provided within \ XML data are ignored in order to avoid the change of schema instance. Set this \ option to `True` to activate dynamic schema loading using schema location hints. :raises: :exc:`XMLSchemaValidationError` if the XML data instance is invalid. """ for error in self.iter_errors(source, path, schema_path, use_defaults, namespaces, max_depth, extra_validator, validation_hook, allow_empty, use_location_hints, validation='strict'): raise error def is_valid(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NamespacesType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, allow_empty: bool = True, use_location_hints: bool = False) -> bool: """ Like :meth:`validate` except that does not raise an exception but returns ``True`` if the XML data instance is valid, ``False`` if it is invalid. """ error = next(self.iter_errors(source, path, schema_path, use_defaults, namespaces, max_depth, extra_validator, validation_hook, allow_empty, use_location_hints), None) return error is None def iter_errors(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, use_defaults: bool = True, namespaces: Optional[NamespacesType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, allow_empty: bool = True, use_location_hints: bool = False, validation: str = 'lax') \ -> Iterator[XMLSchemaValidationError]: """ Creates an iterator for the errors generated by the validation of an XML data against the XSD schema/component instance. Accepts the same arguments of :meth:`validate`. """ self.check_validator(validation='lax') if isinstance(source, XMLResource): resource: XMLResource = source else: resource = XMLResource(source, defuse=self.defuse, timeout=self.timeout) if not schema_path: schema_path = resource.get_absolute_path(path) converter = NamespaceMapper(namespaces, source=resource) namespaces = converter.namespaces namespace = resource.namespace or namespaces.get('', '') try: schema = self.get_schema(namespace) except KeyError: schema = self identities: Dict[XsdIdentity, IdentityCounter] = {} ancestors: List[ElementType] = [] prev_ancestors: List[ElementType] = [] kwargs: Dict[Any, Any] = { 'level': resource.lazy_depth or bool(path), 'source': resource, 'namespaces': namespaces, 'converter': converter, 'id_map': Counter[str](), 'identities': identities, 'inherited': {}, 'validation': validation, } if not use_defaults: kwargs['use_defaults'] = False if use_location_hints and not resource.is_lazy(): kwargs['use_location_hints'] = True if self.XSD_VERSION == '1.1': kwargs['errors'] = [] if max_depth is not None: kwargs['max_depth'] = max_depth if extra_validator is not None: kwargs['extra_validator'] = extra_validator if validation_hook is not None: kwargs['validation_hook'] = validation_hook if path: selector = resource.iterfind(path, namespaces, ancestors=ancestors) else: selector = resource.iter_depth(mode=4, ancestors=ancestors) elem: Optional[ElementType] = None for elem in selector: if elem is resource.root: if resource.lazy_depth: kwargs['level'] = 0 kwargs['identities'] = {} kwargs['max_depth'] = resource.lazy_depth else: if prev_ancestors != ancestors: k = 0 for k in range(min(len(ancestors), len(prev_ancestors))): if ancestors[k] is not prev_ancestors[k]: break path_ = f"{'/'.join(e.tag for e in ancestors)}/ancestor-or-self::node()" xsd_ancestors = cast(List[XsdElement], schema.findall(path_, converter.namespaces)[1:]) # Clear identity constraints counters for k, e in enumerate(xsd_ancestors[k:], start=k): for identity in e.identities: if identity in identities: identities[identity].reset(ancestors[k]) else: identities[identity] = identity.get_counter(ancestors[k]) prev_ancestors = ancestors[:] xsd_element = schema.get_element(elem.tag, schema_path, namespaces) if xsd_element is None: if XSI_TYPE in elem.attrib: xsd_element = self.create_element(name=elem.tag) elif elem is not resource.root and ancestors: continue else: reason = _("{!r} is not an element of the schema").format(elem) yield schema.validation_error( 'lax', reason, elem, source=resource, namespaces=namespaces ) return try: for result in xsd_element.iter_decode(elem, **kwargs): if isinstance(result, XMLSchemaValidationError): yield result else: del result except XMLSchemaStopValidation: pass else: if elem is None and not allow_empty: assert path is not None reason = _("the provided path selects nothing to validate") yield schema.validation_error( 'lax', reason, source=resource, namespaces=namespaces ) return if kwargs['identities'] is not identities: for identity, counter in kwargs['identities'].items(): identities[identity].counter.update(counter.counter) kwargs['identities'] = identities yield from self._validate_references(**kwargs) def _validate_references(self, source: XMLResource, validation: str = 'lax', id_map: Optional[Counter[str]] = None, identities: Optional[IdentityMapType] = None, **kwargs: Any) -> Iterator[XMLSchemaValidationError]: # Check unresolved IDREF values if id_map is not None: for k, v in id_map.items(): if v == 0: msg = _("IDREF %r not found in XML document") % k yield self.validation_error(validation, msg, source.root) # Check still enabled key references (lazy validation cases) if identities is not None: for identity, counter in identities.items(): if counter.enabled and isinstance(identity, XsdKeyref): for error in cast(KeyrefCounter, counter).iter_errors(identities): yield self.validation_error(validation, error, source.root, **kwargs) def raw_decoder(self, source: XMLResource, path: Optional[str] = None, schema_path: Optional[str] = None, validation: str = 'lax', namespaces: Optional[NamespacesType] = None, **kwargs: Any) \ -> Iterator[Union[Any, XMLSchemaValidationError]]: """Returns a generator for decoding a resource.""" if path: selector = source.iterfind(path, namespaces) else: selector = source.iter_depth(mode=2) for elem in selector: xsd_element = self.get_element(elem.tag, schema_path, namespaces) if xsd_element is None: if XSI_TYPE in elem.attrib: xsd_element = self.create_element(name=elem.tag) else: reason = _("{!r} is not an element of the schema").format(elem) yield self.validation_error(validation, reason, elem, source=source, namespaces=namespaces) continue yield from xsd_element.iter_decode(elem, validation, **kwargs) if 'max_depth' not in kwargs: yield from self._validate_references(source, validation=validation, **kwargs) def iter_decode(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, validation: str = 'lax', process_namespaces: bool = True, namespaces: Optional[NamespacesType] = None, use_defaults: bool = True, use_location_hints: bool = False, decimal_type: Optional[Type[Any]] = None, datetime_types: bool = False, binary_types: bool = False, converter: Optional[ConverterType] = None, filler: Optional[FillerType] = None, fill_missing: bool = False, keep_empty: bool = False, keep_unknown: bool = False, process_skipped: bool = False, max_depth: Optional[int] = None, depth_filler: Optional[DepthFillerType] = None, extra_validator: Optional[ExtraValidatorType] = None, validation_hook: Optional[ValidationHookType] = None, value_hook: Optional[ValueHookType] = None, element_hook: Optional[ElementHookType] = None, errors: Optional[List[XMLSchemaValidationError]] = None, **kwargs: Any) -> Iterator[Union[Any, XMLSchemaValidationError]]: """ Creates an iterator for decoding an XML source to a data structure. :param source: the source of XML data. Can be an :class:`XMLResource` instance, a \ path to a file or a URI of a resource or an opened file-like object or an Element \ instance or an ElementTree instance or a string containing the XML data. :param path: is an optional XPath expression that matches the elements of the XML \ data that have to be decoded. If not provided the XML root element is selected. :param schema_path: an alternative XPath expression to select the XSD element \ to use for decoding. Useful if the root of the XML data doesn't match an XSD \ global element of the schema. :param validation: defines the XSD validation mode to use for decode, can be \ 'strict', 'lax' or 'skip'. :param process_namespaces: whether to use namespace information in the \ decoding process, using the map provided with the argument *namespaces* \ and the namespace declarations extracted from the XML document. :param namespaces: is an optional mapping from namespace prefix to URI that \ integrate/override the root namespace declarations of the XML source. \ In case of prefix collision an alternate prefix is used for the root \ XML namespace declaration. :param use_defaults: whether to use default values for filling missing data. :param use_location_hints: for default schema locations hints provided within \ XML data are ignored in order to avoid the change of schema instance. Set this \ option to `True` to activate dynamic schema loading using schema location hints. :param decimal_type: conversion type for `Decimal` objects (generated by \ `xs: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 kept decoded, otherwise their origin XML string is returned. :param binary_types: if set to `True` xs:hexBinary and xs:base64Binary types \ are kept decoded, otherwise their origin XML string is returned. :param converter: an :class:`XMLSchemaConverter` subclass or instance to use \ for decoding. :param filler: an optional callback function to fill undecodable data with a \ typed value. The callback function must accept one positional argument, that \ can be an XSD Element or an attribute declaration. If not provided undecodable \ data is replaced by `None`. :param fill_missing: if set to `True` the decoder fills also missing attributes. \ The filling value is `None` or a typed value if the *filler* callback is provided. :param keep_empty: if set to `True` empty elements that are valid are decoded with \ an empty string value instead of a `None`. :param keep_unknown: if set to `True` unknown tags are kept and are decoded with \ *xs:anyType*. For default unknown tags not decoded by a wildcard are discarded. :param process_skipped: process XML data that match a wildcard with \ `processContents='skip'`. :param max_depth: maximum level of decoding, for default there is no limit. \ With lazy resources is set to `source.lazy_depth` for managing lazy decoding. :param depth_filler: an optional callback function to replace data over the \ *max_depth* level. The callback function must accept one positional argument, that \ can be an XSD Element. If not provided deeper data are replaced with `None` values. :param extra_validator: an optional function for performing non-standard \ validations on XML data. The provided function is called for each traversed \ element, with the XML element as 1st argument and the corresponding XSD \ element as 2nd argument. It can be also a generator function and has to \ raise/yield :exc:`XMLSchemaValidationError` exceptions. :param validation_hook: an optional function for stopping or changing \ validated decoding at element level. The provided function must accept two \ arguments, the XML element and the matching XSD element. If the value returned \ by this function is evaluated to false then the decoding process continues \ without changes, otherwise the decoding process is stopped or changed. If the \ value returned is a validation mode the decoding process continues changing the \ current validation mode to the returned value, otherwise the element and its \ content are not decoded. :param value_hook: an optional function that will be called with any decoded \ atomic value and the XSD type used for decoding. The return value will be used \ instead of the original value. :param element_hook: an optional function that is called with decoded element \ data before calling the converter decode method. Takes an `ElementData` \ instance plus optionally the XSD element and the XSD type, and returns a \ new `ElementData` instance. :param errors: optional internal collector for validation errors. :param kwargs: keyword arguments with other options for converters. :return: yields a decoded data object, eventually preceded by a sequence of \ validation or decoding errors. """ self.check_validator(validation) if isinstance(source, XMLResource): resource: XMLResource = source else: resource = XMLResource(source, defuse=self.defuse, timeout=self.timeout) if not schema_path and path: schema_path = resource.get_absolute_path(path) converter = self.get_converter( converter, namespaces=namespaces, process_namespaces=process_namespaces, source=resource, **kwargs ) namespaces = converter.namespaces namespace = resource.namespace or namespaces.get('', '') schema = self.get_schema(namespace) kwargs = { 'converter': converter, 'namespaces': namespaces, 'source': resource, 'id_map': Counter[str](), 'identities': {}, 'inherited': {}, } if not use_defaults: kwargs['use_defaults'] = False if use_location_hints and not resource.is_lazy(): kwargs['use_location_hints'] = True if self.XSD_VERSION == '1.1': kwargs['errors'] = [] if decimal_type is not None: kwargs['decimal_type'] = decimal_type if datetime_types: kwargs['datetime_types'] = True if binary_types: kwargs['binary_types'] = True if filler is not None: kwargs['filler'] = filler if fill_missing: kwargs['fill_missing'] = True if keep_empty: kwargs['keep_empty'] = True if keep_unknown: kwargs['keep_unknown'] = True if process_skipped: kwargs['process_skipped'] = True if max_depth is not None: kwargs['max_depth'] = max_depth if depth_filler is not None: kwargs['depth_filler'] = depth_filler if extra_validator is not None: kwargs['extra_validator'] = extra_validator if validation_hook is not None: kwargs['validation_hook'] = validation_hook if value_hook is not None: kwargs['value_hook'] = value_hook if element_hook is not None: kwargs['element_hook'] = element_hook if errors is not None: kwargs['errors'] = errors if path: selector = resource.iterfind(path, namespaces) elif not resource.is_lazy(): selector = iter((resource.root,)) else: decoder = self.raw_decoder( schema_path=resource.get_absolute_path(), validation=validation, **kwargs ) kwargs['depth_filler'] = lambda x: decoder kwargs['max_depth'] = resource.lazy_depth selector = resource.iter_depth(mode=3) for elem in selector: xsd_element = schema.get_element(elem.tag, schema_path, namespaces) if xsd_element is None: if XSI_TYPE in elem.attrib: xsd_element = self.create_element(name=elem.tag) else: reason = _("{!r} is not an element of the schema").format(elem) yield schema.validation_error( validation, reason, elem, source=resource, namespaces=namespaces ) return yield from xsd_element.iter_decode(elem, validation, **kwargs) if 'max_depth' not in kwargs: yield from self._validate_references(validation=validation, **kwargs) def decode(self, source: Union[XMLSourceType, XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, validation: str = 'strict', *args: Any, **kwargs: Any) -> DecodeType[Any]: """ Decodes XML data. Takes the same arguments of the method :meth:`iter_decode`. """ data, errors = [], [] for result in self.iter_decode(source, path, schema_path, validation, *args, **kwargs): if not isinstance(result, XMLSchemaValidationError): data.append(result) elif validation == 'lax': errors.append(result) elif validation == 'strict': raise result if not data: return (None, errors) if validation == 'lax' else None elif len(data) == 1: return (data[0], errors) if validation == 'lax' else data[0] else: return (data, errors) if validation == 'lax' else data to_dict = decode def to_objects(self, source: Union[XMLSourceType, XMLResource], with_bindings: bool = False, **kwargs: Any) -> DecodeType['dataobjects.DataElement']: """ Decodes XML data to Python data objects. :param source: the XML data. Can be a string for an attribute or for a simple \ type components or a dictionary for an attribute group or an ElementTree's \ Element for other components. :param with_bindings: if `True` is provided the decoding is done using \ :class:`DataBindingConverter` that used XML data binding classes. For \ default the objects are instances of :class:`DataElement` and uses the \ :class:`DataElementConverter`. :param kwargs: other optional keyword arguments for the method \ :func:`iter_decode`, except the argument *converter*. """ if with_bindings: return self.decode(source, converter=dataobjects.DataBindingConverter, **kwargs) return self.decode(source, converter=dataobjects.DataElementConverter, **kwargs) def iter_encode(self, obj: Any, path: Optional[str] = None, validation: str = 'lax', namespaces: Optional[NamespacesType] = None, use_defaults: bool = True, converter: Optional[ConverterType] = None, unordered: bool = False, process_skipped: bool = False, max_depth: Optional[int] = None, **kwargs: Any) -> Iterator[Union[ElementType, XMLSchemaValidationError]]: """ Creates an iterator for encoding a data structure to an ElementTree's Element. :param obj: the data that has to be encoded to XML data. :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 use_defaults: whether to use default values for filling missing data. :param converter: an :class:`XMLSchemaConverter` subclass or instance to use for \ the encoding. :param unordered: a flag for explicitly activating unordered encoding mode for \ content model data. This mode uses content models for a reordered-by-model \ iteration of the child elements. :param process_skipped: process XML decoded data that match a wildcard with \ `processContents='skip'`. :param max_depth: maximum level of encoding, for default there is no limit. :param kwargs: keyword arguments with other options for building the \ converter instance. :return: yields an Element instance/s or validation/encoding errors. """ self.check_validator(validation) if not self.elements: msg = _("encoding needs at least one XSD element declaration") raise XMLSchemaValueError(msg) converter = self.get_converter( converter, namespaces=namespaces, source=obj, **kwargs ) namespaces = converter.namespaces kwargs = { 'level': 0, 'converter': converter, 'namespaces': namespaces, } if not use_defaults: kwargs['use_defaults'] = False if unordered: kwargs['unordered'] = True if process_skipped: kwargs['process_skipped'] = process_skipped if max_depth is not None: kwargs['max_depth'] = max_depth xsd_element = None if path is not None: match = re.search(r'[{\w]', path) if match: namespace = get_namespace(path[match.start():], namespaces) schema = self.get_schema(namespace) xsd_element = schema.find(path, namespaces) elif len(self.elements) == 1: xsd_element = list(self.elements.values())[0] else: root_elements = self.root_elements if len(root_elements) == 1: xsd_element = root_elements[0] elif isinstance(obj, (converter.dict, dict)) and len(obj) == 1: for key in obj: match = re.search(r'[{\w]', key) if match: namespace = get_namespace(key[match.start():], namespaces) schema = self.get_schema(namespace) xsd_element = schema.find(key, namespaces) if not isinstance(xsd_element, XsdElement): if path is not None: reason = _("the path %r doesn't match any element of the schema!") % path else: reason = _("unable to select an element for encoding data, " "provide a valid 'path' argument.") raise XMLSchemaEncodeError(self, obj, self.elements, reason, namespaces=namespaces) else: yield from xsd_element.iter_encode(obj, validation, **kwargs) def encode(self, obj: Any, path: Optional[str] = None, validation: str = 'strict', *args: Any, **kwargs: Any) -> EncodeType[Any]: """ Encodes to XML data. Takes the same arguments of the method :meth:`iter_encode`. :return: An ElementTree's Element or a list containing a sequence of ElementTree's \ elements if the argument *path* matches multiple XML data chunks. 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. """ data, errors = [], [] result: Union[ElementType, XMLSchemaValidationError] for result in self.iter_encode(obj, path, validation, *args, **kwargs): if not isinstance(result, XMLSchemaValidationError): data.append(result) elif validation == 'lax': errors.append(result) elif validation == 'strict': raise result if not data: return (None, errors) if validation == 'lax' else None elif len(data) == 1: if errors: resource = XMLResource(data[0]) for e in errors: e.source = resource return (data[0], errors) if validation == 'lax' else data[0] else: return (data, errors) if validation == 'lax' else data to_etree = encode
(source: xmlschema.resources.XMLResource, namespace: Optional[str] = None, validation: str = 'strict', global_maps: Optional[xmlschema.validators.global_maps.XsdGlobals] = None, converter: Optional[~T] = None, locations: xmlschema.namespaces.NamespaceResourcesMap = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, uri_mapper: Optional[~T] = None, build: bool = True, use_meta: bool = True, use_fallback: bool = True, use_xpath3: bool = False, loglevel: Union[str, int, NoneType] = None) -> None
713,611
xmlschema.validators.exceptions
XMLSchemaChildrenValidationError
Raised when a child element is not validated. :param validator: the XSD validator. :param elem: the not validated XML element. :param index: the child index. :param particle: the model particle that generated the error. Maybe the validator itself. :param occurs: the particle occurrences. :param expected: the expected element tags/object names. :param source: the XML resource that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI.
class XMLSchemaChildrenValidationError(XMLSchemaValidationError): """ Raised when a child element is not validated. :param validator: the XSD validator. :param elem: the not validated XML element. :param index: the child index. :param particle: the model particle that generated the error. Maybe the validator itself. :param occurs: the particle occurrences. :param expected: the expected element tags/object names. :param source: the XML resource that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. """ invalid_tag: Optional[str] """The tag of the invalid child element, `None` in case of an incomplete content.""" def __init__(self, validator: 'XsdValidator', elem: ElementType, index: int, particle: ModelParticleType, occurs: int = 0, expected: Optional[Iterable[SchemaElementType]] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: self.index = index self.particle = particle self.occurs = occurs self.expected = expected if index >= len(elem): self.invalid_tag = None tag = get_prefixed_qname(elem.tag, validator.namespaces, use_empty=False) reason = _("The content of element %r is not complete.") % tag else: self.invalid_tag = elem[index].tag tag = get_prefixed_qname(self.invalid_tag, validator.namespaces, use_empty=False) reason = _("Unexpected child with tag %r at position %d.") % (tag, index + 1) if occurs and particle.min_occurs > occurs: reason += " The particle %r occurs %d times but the minimum is %d." % ( particle, occurs, particle.min_occurs ) elif particle.max_occurs is not None and particle.max_occurs < occurs: reason += " The particle %r occurs %r times but the maximum is %r." % ( particle, occurs, particle.max_occurs ) if expected is None: pass else: expected_tags = [] for xsd_element in expected: name = xsd_element.display_name if name is not None: expected_tags.append(name) elif getattr(xsd_element, 'process_contents', '') == 'strict': expected_tags.append( 'from %r namespace/s' % xsd_element.namespace # type: ignore[union-attr] ) if not expected_tags: pass elif len(expected_tags) > 1: reason += _(" Tag (%s) expected.") % ' | '.join(repr(tag) for tag in expected_tags) elif expected_tags[0].startswith('from '): reason += _(" Tag %s expected.") % expected_tags[0] else: reason += _(" Tag %r expected.") % expected_tags[0] super().__init__(validator, elem, reason, source, namespaces) @property def invalid_child(self) -> Optional[ElementType]: """ The invalid child element, if any, `None` otherwise. It's `None` in case of incomplete content or if the parent has been cleared during lazy validation. """ try: return self.elem[self.index] if self.elem is not None else None except IndexError: return None # in case of incomplete content or lazy trees
(validator: 'XsdValidator', elem: Optional[~T], index: int, particle: Optional[~T], occurs: int = 0, expected: Optional[Iterable[Optional[~T]]] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,612
xmlschema.validators.exceptions
__init__
null
def __init__(self, validator: 'XsdValidator', elem: ElementType, index: int, particle: ModelParticleType, occurs: int = 0, expected: Optional[Iterable[SchemaElementType]] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: self.index = index self.particle = particle self.occurs = occurs self.expected = expected if index >= len(elem): self.invalid_tag = None tag = get_prefixed_qname(elem.tag, validator.namespaces, use_empty=False) reason = _("The content of element %r is not complete.") % tag else: self.invalid_tag = elem[index].tag tag = get_prefixed_qname(self.invalid_tag, validator.namespaces, use_empty=False) reason = _("Unexpected child with tag %r at position %d.") % (tag, index + 1) if occurs and particle.min_occurs > occurs: reason += " The particle %r occurs %d times but the minimum is %d." % ( particle, occurs, particle.min_occurs ) elif particle.max_occurs is not None and particle.max_occurs < occurs: reason += " The particle %r occurs %r times but the maximum is %r." % ( particle, occurs, particle.max_occurs ) if expected is None: pass else: expected_tags = [] for xsd_element in expected: name = xsd_element.display_name if name is not None: expected_tags.append(name) elif getattr(xsd_element, 'process_contents', '') == 'strict': expected_tags.append( 'from %r namespace/s' % xsd_element.namespace # type: ignore[union-attr] ) if not expected_tags: pass elif len(expected_tags) > 1: reason += _(" Tag (%s) expected.") % ' | '.join(repr(tag) for tag in expected_tags) elif expected_tags[0].startswith('from '): reason += _(" Tag %s expected.") % expected_tags[0] else: reason += _(" Tag %r expected.") % expected_tags[0] super().__init__(validator, elem, reason, source, namespaces)
(self, validator: 'XsdValidator', elem: Optional[~T], index: int, particle: Optional[~T], occurs: int = 0, expected: Optional[Iterable[Optional[~T]]] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,613
xmlschema.validators.exceptions
__repr__
null
def __repr__(self) -> str: return '%s(reason=%r)' % (self.__class__.__name__, self.reason)
(self) -> str
713,614
xmlschema.validators.exceptions
__setattr__
null
def __setattr__(self, name: str, value: Any) -> None: if name == 'elem' and value is not None: if not is_etree_element(value): raise XMLSchemaValueError( "'elem' attribute requires an Element, not %r." % type(value) ) if isinstance(self.source, XMLResource): self._path = etree_getpath( elem=value, root=self.source.root, namespaces=self.namespaces, relative=False, add_position=True ) if self.source.is_lazy(): value = None # Don't save the element of a lazy resource super().__setattr__(name, value)
(self, name: str, value: Any) -> NoneType
713,615
xmlschema.validators.exceptions
__str__
null
def __str__(self) -> str: chunks = ['%s:\n' % self.message] if self.reason is not None: chunks.append('Reason: %s\n' % self.reason) if hasattr(self.validator, 'tostring'): component_as_string = self.validator.tostring(' ', 20) chunks.append("Schema component:\n\n%s\n" % component_as_string) if is_etree_element(self.elem): chunks.append(f"Instance type: {type(self.elem)}\n") instance_as_string = self.get_elem_as_string(indent=' ', max_lines=20) else: chunks.append(f"Instance type: {type(self.obj)}\n") instance_as_string = self.get_obj_as_string(indent=' ', max_lines=20) if hasattr(self.elem, 'sourceline'): line = getattr(self.elem, 'sourceline') chunks.append(f"Instance (line {line!r}):\n\n{instance_as_string}\n") else: chunks.append(f"Instance:\n\n{instance_as_string}\n") if self.path is not None: chunks.append("Path: %s\n" % self.path) return '\n'.join(chunks) if len(chunks) > 1 else chunks[0][:-2]
(self) -> str
713,616
xmlschema.validators.exceptions
get_elem_as_string
Returns a string representation of elem attribute.
def get_elem_as_string(self, indent: str = '', max_lines: Optional[int] = None) -> str: """Returns a string representation of elem attribute.""" kwargs = { 'elem': self.elem, 'namespaces': self.namespaces, 'indent': indent, 'max_lines': max_lines } try: return cast(str, etree_tostring(**kwargs)) # type: ignore[arg-type] except (ValueError, TypeError): return indent + repr(self.elem)
(self, indent: str = '', max_lines: Optional[int] = None) -> str
713,617
xmlschema.validators.exceptions
get_obj_as_string
Return a string representation of obj attribute, with optional indentation and an optional limit on lines.
def get_obj_as_string(self, indent: str = '', max_lines: Optional[int] = None) -> str: """ Return a string representation of obj attribute, with optional indentation and an optional limit on lines. """ if is_etree_element(self.obj): return self.get_elem_as_string(indent, max_lines) pp = PrettyPrinter(indent=2, depth=6) obj_as_string = pp.pformat(self.obj) if indent: obj_as_string = textwrap.indent(obj_as_string, prefix=indent) if max_lines and len(obj_as_string.splitlines()) > max_lines: obj_as_string = '\n'.join(obj_as_string.splitlines()[:max_lines - 3]) obj_as_string += f'\n\n{indent}...\n{indent}...' return obj_as_string
(self, indent: str = '', max_lines: Optional[int] = None) -> str
713,618
xmlschema.converters.default
XMLSchemaConverter
Generic XML Schema based converter class. A converter is used to compose decoded XML data for an Element into a data structure and to build an Element from encoded data structure. There are two methods for interfacing the converter with the decoding/encoding process. The method *element_decode* accepts an ElementData tuple, containing the element parts, and returns a data structure. The method *element_encode* accepts a data structure and returns an ElementData tuple. For default character data parts are ignored. Prefixes and text key can be changed also using alphanumeric values but ambiguities with schema elements could affect XML data re-encoding. :param namespaces: map from namespace prefixes to URI. :param dict_class: dictionary class to use for decoded data. Default is `dict`. :param list_class: list class to use for decoded data. Default is `list`. :param etree_element_class: the class that has to be used to create new XML elements, if not provided uses the ElementTree's Element class. :param text_key: is the key to apply to element's decoded text data. :param attr_prefix: controls the mapping of XML attributes, to the same name or with a prefix. If `None` the converter ignores attributes. :param cdata_prefix: is used for including and prefixing the character data parts of a mixed content, that are labeled with an integer instead of a string. Character data parts are ignored if this argument is `None`. :param indent: number of spaces for XML indentation (default is 4). :param process_namespaces: whether to use namespace information in name mapping methods. If set to `False` then the name mapping methods simply return the provided name. :param strip_namespaces: if set to `True` removes namespace declarations from data and namespace information from names, during decoding or encoding. Defaults to `False`. :param xmlns_processing: defines the processing mode of XML namespace declarations. Can be 'stacked', 'collapsed', 'root-only' or 'none', with the meaning defined for the `NamespaceMapper` base class. For default the xmlns processing mode is chosen between 'stacked', 'collapsed' and 'none', depending on the provided XML source and the capabilities and the settings of the converter instance. :param source: the origin of XML data. Con be an `XMLResource` instance or `None`. :param preserve_root: if set to `True` the root element is preserved, wrapped into a single-item dictionary. Applicable only to default converter, to :class:`UnorderedConverter` and to :class:`ParkerConverter`. :param force_dict: if set to `True` complex elements with simple content are decoded with a dictionary also if there are no decoded attributes. Applicable only to default converter and to :class:`UnorderedConverter`. Defaults to `False`. :param force_list: if set to `True` child elements are decoded within a list in any case. Applicable only to default converter and to :class:`UnorderedConverter`. Defaults to `False`. :ivar dict: dictionary class to use for decoded data. :ivar list: list class to use for decoded data. :ivar etree_element_class: Element class to use :ivar text_key: key for decoded Element text :ivar attr_prefix: prefix for attribute names :ivar cdata_prefix: prefix for character data parts :ivar indent: indentation to use for rebuilding XML trees :ivar preserve_root: preserve the root element on decoding :ivar force_dict: force dictionary for complex elements with simple content :ivar force_list: force list for child elements
class XMLSchemaConverter(NamespaceMapper): """ Generic XML Schema based converter class. A converter is used to compose decoded XML data for an Element into a data structure and to build an Element from encoded data structure. There are two methods for interfacing the converter with the decoding/encoding process. The method *element_decode* accepts an ElementData tuple, containing the element parts, and returns a data structure. The method *element_encode* accepts a data structure and returns an ElementData tuple. For default character data parts are ignored. Prefixes and text key can be changed also using alphanumeric values but ambiguities with schema elements could affect XML data re-encoding. :param namespaces: map from namespace prefixes to URI. :param dict_class: dictionary class to use for decoded data. Default is `dict`. :param list_class: list class to use for decoded data. Default is `list`. :param etree_element_class: the class that has to be used to create new XML elements, \ if not provided uses the ElementTree's Element class. :param text_key: is the key to apply to element's decoded text data. :param attr_prefix: controls the mapping of XML attributes, to the same name or \ with a prefix. If `None` the converter ignores attributes. :param cdata_prefix: is used for including and prefixing the character data parts \ of a mixed content, that are labeled with an integer instead of a string. \ Character data parts are ignored if this argument is `None`. :param indent: number of spaces for XML indentation (default is 4). :param process_namespaces: whether to use namespace information in name mapping \ methods. If set to `False` then the name mapping methods simply return the \ provided name. :param strip_namespaces: if set to `True` removes namespace declarations from data and \ namespace information from names, during decoding or encoding. Defaults to `False`. :param xmlns_processing: defines the processing mode of XML namespace declarations. \ Can be 'stacked', 'collapsed', 'root-only' or 'none', with the meaning defined for \ the `NamespaceMapper` base class. For default the xmlns processing mode is chosen \ between 'stacked', 'collapsed' and 'none', depending on the provided XML source \ and the capabilities and the settings of the converter instance. :param source: the origin of XML data. Con be an `XMLResource` instance or `None`. :param preserve_root: if set to `True` the root element is preserved, wrapped into a \ single-item dictionary. Applicable only to default converter, to \ :class:`UnorderedConverter` and to :class:`ParkerConverter`. :param force_dict: if set to `True` complex elements with simple content are decoded \ with a dictionary also if there are no decoded attributes. Applicable only to default \ converter and to :class:`UnorderedConverter`. Defaults to `False`. :param force_list: if set to `True` child elements are decoded within a list in any case. \ Applicable only to default converter and to :class:`UnorderedConverter`. Defaults to `False`. :ivar dict: dictionary class to use for decoded data. :ivar list: list class to use for decoded data. :ivar etree_element_class: Element class to use :ivar text_key: key for decoded Element text :ivar attr_prefix: prefix for attribute names :ivar cdata_prefix: prefix for character data parts :ivar indent: indentation to use for rebuilding XML trees :ivar preserve_root: preserve the root element on decoding :ivar force_dict: force dictionary for complex elements with simple content :ivar force_list: force list for child elements """ ns_prefix: str dict: Type[Dict[str, Any]] list: Type[List[Any]] etree_element_class: Type[Element] __slots__ = ('dict', 'list', 'etree_element_class', 'text_key', 'ns_prefix', 'attr_prefix', 'cdata_prefix', 'indent', 'preserve_root', 'force_dict', 'force_list') def __init__(self, namespaces: Optional[NamespacesType] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, etree_element_class: Optional[Type[Element]] = None, text_key: Optional[str] = '$', attr_prefix: Optional[str] = '@', cdata_prefix: Optional[str] = None, indent: int = 4, process_namespaces: bool = True, strip_namespaces: bool = False, xmlns_processing: Optional[str] = None, source: Optional[XMLResource] = None, preserve_root: bool = False, force_dict: bool = False, force_list: bool = False, **kwargs: Any) -> None: if dict_class is not None: self.dict = dict_class else: self.dict = dict if list_class is not None: self.list = list_class else: self.list = list if etree_element_class is not None: self.etree_element_class = etree_element_class else: self.etree_element_class = Element self.text_key = text_key self.attr_prefix = attr_prefix self.cdata_prefix = cdata_prefix self.ns_prefix = 'xmlns' if attr_prefix is None else f'{attr_prefix}xmlns' self.indent = indent self.preserve_root = preserve_root self.force_dict = force_dict self.force_list = force_list super().__init__( namespaces, process_namespaces, strip_namespaces, xmlns_processing, source ) def __setattr__(self, name: str, value: Any) -> None: if name in {'attr_prefix', 'text_key', 'cdata_prefix'}: if value is not None and not isinstance(value, str): msg = "%(name)r must be a <class 'str'> instance or None, not %(type)r" raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)}) elif name in {'strip_namespaces', 'preserve_root', 'force_dict', 'force_list'}: if not isinstance(value, bool): msg = "%(name)r must be a <class 'bool'> instance, not %(type)r" raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)}) elif name == 'indent': if isinstance(value, bool) or not isinstance(value, int): msg = "%(name)r must be a <class 'int'> instance, not %(type)r" raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)}) elif name == 'dict': if not issubclass(value, MutableMapping): msg = "%(name)r must be a MutableMapping object, not %(type)r" raise XMLSchemaTypeError(msg % {'name': 'dict_class', 'type': type(value)}) elif name == 'list': if not issubclass(value, MutableSequence): msg = "%(name)r must be a MutableSequence object, not %(type)r" raise XMLSchemaTypeError(msg % {'name': 'list_class', 'type': type(value)}) super().__setattr__(name, value) @property def xmlns_processing_default(self) -> str: """ Returns the default of the xmlns processing mode, used if `None` is provided. """ if isinstance(self.source, XMLResource): if getattr(self.element_decode, 'stackable', False): return 'stacked' else: return 'collapsed' elif getattr(self.element_encode, 'stackable', False): return 'stacked' else: return 'collapsed' @property def lossy(self) -> bool: """The converter ignores some kind of XML data during decoding/encoding.""" return self.cdata_prefix is None or self.text_key is None or self.attr_prefix is None @property def losslessly(self) -> bool: """ The XML data is decoded without loss of quality, neither on data nor on data model shape. Only losslessly converters can be always used to encode to an XML data that is strictly conformant to the schema. """ return False @property def loss_xmlns(self) -> bool: """The converter ignores XML namespace information during decoding/encoding.""" return not self._use_namespaces def copy(self, keep_namespaces: bool = True, **kwargs: Any) -> 'XMLSchemaConverter': """ Creates a new converter instance from the existing, replacing options provided with keyword arguments. :param keep_namespaces: whether to keep the namespaces of the converter \ if they are not replaced by a keyword argument. """ namespaces = kwargs.get('namespaces', self._namespaces if keep_namespaces else None) xmlns_processing = None if 'source' in kwargs else self.xmlns_processing return type(self)( namespaces=namespaces, dict_class=kwargs.get('dict_class', self.dict), list_class=kwargs.get('list_class', self.list), etree_element_class=kwargs.get('etree_element_class', self.etree_element_class), text_key=kwargs.get('text_key', self.text_key), attr_prefix=kwargs.get('attr_prefix', self.attr_prefix), cdata_prefix=kwargs.get('cdata_prefix', self.cdata_prefix), indent=kwargs.get('indent', self.indent), process_namespaces=kwargs.get('process_namespaces', self.process_namespaces), strip_namespaces=kwargs.get('strip_namespaces', self.strip_namespaces), xmlns_processing=kwargs.get('xmlns_processing', xmlns_processing), source=kwargs.get('source', self.source), preserve_root=kwargs.get('preserve_root', self.preserve_root), force_dict=kwargs.get('force_dict', self.force_dict), force_list=kwargs.get('force_list', self.force_list), ) def map_attributes(self, attributes: Iterable[Tuple[str, Any]]) \ -> Iterator[Tuple[str, Any]]: """ Creates an iterator for converting decoded attributes to a data structure with appropriate prefixes. If the instance has a not-empty map of namespaces registers the mapped URIs and prefixes. :param attributes: A sequence or an iterator of couples with the name of \ the attribute and the decoded value. Default is `None` (for `simpleType` \ elements, that don't have attributes). """ if self.attr_prefix is None or not attributes: return else: for name, value in attributes: yield self.attr_prefix + self.map_qname(name), value def map_content(self, content: Iterable[Tuple[str, Any, Any]]) \ -> Iterator[Tuple[str, Any, Any]]: """ A generator function for converting decoded content to a data structure. If the instance has a not-empty map of namespaces registers the mapped URIs and prefixes. :param content: A sequence or an iterator of tuples with the name of the \ element, the decoded value and the `XsdElement` instance associated. """ if not content: return for name, value, xsd_child in content: if isinstance(name, int): if self.cdata_prefix is not None: yield f'{self.cdata_prefix}{name}', value, xsd_child elif name[0] == '{': yield self.map_qname(name), value, xsd_child else: yield name, value, xsd_child def etree_element(self, tag: str, text: Optional[str] = None, children: Optional[List[Element]] = None, attrib: Optional[Dict[str, str]] = None, level: int = 0) -> Element: """ Builds an ElementTree's Element using arguments and the element class and the indent spacing stored in the converter instance. :param tag: the Element tag string. :param text: the Element text. :param children: the list of Element children/subelements. :param attrib: a dictionary with Element attributes. :param level: the level related to the encoding process (0 means the root). :return: an instance of the Element class is set for the converter instance. """ if type(self.etree_element_class) is type(Element): if attrib is None: elem = self.etree_element_class(tag) else: elem = self.etree_element_class(tag, self.dict(attrib)) else: # FIXME: need a more refined check nsmap = {prefix if prefix else None: uri for prefix, uri in self._namespaces.items() if uri} elem = self.etree_element_class(tag, nsmap=nsmap) # type: ignore[arg-type] elem.attrib.update(attrib) # type: ignore[arg-type] if children: elem.extend(children) elem.text = text or '\n' + ' ' * self.indent * (level + 1) elem.tail = '\n' + ' ' * self.indent * level else: elem.text = text elem.tail = '\n' + ' ' * self.indent * level return elem def is_xmlns(self, name: str) -> bool: """Returns `True` if the name is a xmlns declaration.""" return name.startswith(self.ns_prefix) and \ (name == self.ns_prefix or name.startswith(f'{self.ns_prefix}:')) def get_effective_xmlns(self, xmlns: XmlnsType, level: int, xsd_element: Optional['XsdElement'] = None) -> XmlnsType: """ Returns the effective xmlns for element decoding/encoding, considering the level and the matching XSD element. At level 0, that is the root of the single decoding/encoding process, all the defined namespaces are returned only if the XSD element is global, otherwise no namespace is returned. """ if level: return xmlns elif xsd_element is None or not xsd_element.is_global(): return None else: return [x for x in self._namespaces.items()] def get_xmlns_from_data(self, obj: Any) -> Optional[List[Tuple[str, str]]]: """Returns the XML declarations from decoded element data.""" if not self._use_namespaces or not isinstance(obj, MutableMapping): return None xmlns = [] for name, value in obj.items(): if name == self.ns_prefix: xmlns.append(('', value)) elif name.startswith(f'{self.ns_prefix}:'): xmlns.append((name[len(self.ns_prefix) + 1:], value)) return xmlns @stackable def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: """ Converts a decoded element data to a data structure. :param data: ElementData instance decoded from an Element node. :param xsd_element: the `XsdElement` associated to decode the data. :param xsd_type: optional XSD type for supporting dynamic type through \ *xsi:type* or xs:alternative. :param level: the level related to the decoding process (0 means the root). :return: a data structure containing the decoded data. """ xsd_type = xsd_type or xsd_element.type result_dict = self.dict() xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) def keep_result_dict() -> bool: """ Decide when to keep a result dict in case of an element with simple content. """ if data.attributes or self.force_dict and xsd_type.is_complex(): return True elif not xmlns or not self._use_namespaces: return False namespace = get_namespace(data.tag) if any(x[1] == namespace for x in xmlns): return True if xsd_type.is_qname() and isinstance(data.text, str): try: prefix = data.text.split(':')[0] except IndexError: prefix = '' if any(x[0] == prefix for x in xmlns): return True return False if self._use_namespaces and xmlns: result_dict.update( (f'{self.ns_prefix}:{k}' if k else self.ns_prefix, v) for k, v in xmlns ) if data.attributes: result_dict.update(self.map_attributes(data.attributes)) xsd_group = xsd_type.model_group if xsd_group is None or not data.content: if keep_result_dict(): result_dict.update(self.map_attributes(data.attributes)) if data.text is not None and self.text_key is not None: result_dict[self.text_key] = data.text elif not level and self.preserve_root: return self.dict([(self.map_qname(data.tag), data.text)]) else: return data.text else: if data.attributes: result_dict.update(self.map_attributes(data.attributes)) has_single_group = xsd_group.is_single() for name, value, xsd_child in self.map_content(data.content): try: result = result_dict[name] except KeyError: if xsd_child is None or has_single_group and xsd_child.is_single(): result_dict[name] = self.list([value]) if self.force_list else value else: result_dict[name] = self.list([value]) else: if not isinstance(result, MutableSequence) or not result: result_dict[name] = self.list([result, value]) elif isinstance(result[0], MutableSequence) or \ not isinstance(value, MutableSequence): result.append(value) else: result_dict[name] = self.list([result, value]) if not level and self.preserve_root: return self.dict([(self.map_qname(data.tag), result_dict or None)]) return result_dict or None @stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: """ Extracts XML decoded data from a data structure for encoding into an ElementTree. :param obj: the decoded object. :param xsd_element: the `XsdElement` associated to the decoded data structure. :param level: the level related to the encoding process (0 means the root). :return: an ElementData instance. """ if level or not self.preserve_root: element_name = None elif not isinstance(obj, MutableMapping): raise XMLSchemaTypeError(f"A dictionary expected, got {type(obj)} instead.") elif len(obj) != 1: raise XMLSchemaValueError("The dictionary must have exactly one element.") else: element_name, obj = next(iter(obj.items())) if not isinstance(obj, MutableMapping): if xsd_element.type.simple_type is not None: return ElementData(xsd_element.name, obj, None, {}, None) elif xsd_element.type.mixed and isinstance(obj, (str, bytes)): return ElementData(xsd_element.name, None, [(1, obj)], {}, None) else: return ElementData(xsd_element.name, None, obj, {}, None) text = None content: List[Tuple[Union[int, str], Any]] = [] attributes = {} xmlns = self.set_context(obj, level) if element_name is not None: tag = self.unmap_qname(element_name) if not xsd_element.is_matching(tag, self.default_namespace): raise XMLSchemaValueError("data tag does not match XSD element name") for name, value in obj.items(): if name == self.text_key: text = value elif self.cdata_prefix is not None and \ name.startswith(self.cdata_prefix) and \ name[len(self.cdata_prefix):].isdigit(): index = int(name[len(self.cdata_prefix):]) content.append((index, value)) elif self.is_xmlns(name): continue elif self.attr_prefix and \ name.startswith(self.attr_prefix) and \ name != self.attr_prefix: attr_name = name[len(self.attr_prefix):] ns_name = self.unmap_qname(attr_name, xsd_element.attributes) attributes[ns_name] = value elif not isinstance(value, MutableSequence) or not value: ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value)) content.append((ns_name, value)) elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value[0])) content.extend((ns_name, item) for item in value) else: ns_name = self.unmap_qname(name) xsd_child = xsd_element.match_child(ns_name) if xsd_child is not None: if xsd_child.type and xsd_child.type.is_list(): content.append((ns_name, value)) else: content.extend((ns_name, item) for item in value) elif self.attr_prefix == '' and ns_name in xsd_element.attributes: attributes[ns_name] = value else: content.extend((ns_name, item) for item in value) return ElementData(xsd_element.name, text, content, attributes, xmlns)
(namespaces: Optional[~T] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, etree_element_class: Type[xml.etree.ElementTree.Element] = None, text_key: Optional[str] = '$', attr_prefix: Optional[str] = '@', cdata_prefix: Optional[str] = None, indent: int = 4, process_namespaces: bool = True, strip_namespaces: bool = False, xmlns_processing: Optional[str] = None, source: Optional[xmlschema.resources.XMLResource] = None, preserve_root: bool = False, force_dict: bool = False, force_list: bool = False, **kwargs: Any) -> None
713,632
xmlschema.converters.default
element_encode
Extracts XML decoded data from a data structure for encoding into an ElementTree. :param obj: the decoded object. :param xsd_element: the `XsdElement` associated to the decoded data structure. :param level: the level related to the encoding process (0 means the root). :return: an ElementData instance.
@stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: """ Extracts XML decoded data from a data structure for encoding into an ElementTree. :param obj: the decoded object. :param xsd_element: the `XsdElement` associated to the decoded data structure. :param level: the level related to the encoding process (0 means the root). :return: an ElementData instance. """ if level or not self.preserve_root: element_name = None elif not isinstance(obj, MutableMapping): raise XMLSchemaTypeError(f"A dictionary expected, got {type(obj)} instead.") elif len(obj) != 1: raise XMLSchemaValueError("The dictionary must have exactly one element.") else: element_name, obj = next(iter(obj.items())) if not isinstance(obj, MutableMapping): if xsd_element.type.simple_type is not None: return ElementData(xsd_element.name, obj, None, {}, None) elif xsd_element.type.mixed and isinstance(obj, (str, bytes)): return ElementData(xsd_element.name, None, [(1, obj)], {}, None) else: return ElementData(xsd_element.name, None, obj, {}, None) text = None content: List[Tuple[Union[int, str], Any]] = [] attributes = {} xmlns = self.set_context(obj, level) if element_name is not None: tag = self.unmap_qname(element_name) if not xsd_element.is_matching(tag, self.default_namespace): raise XMLSchemaValueError("data tag does not match XSD element name") for name, value in obj.items(): if name == self.text_key: text = value elif self.cdata_prefix is not None and \ name.startswith(self.cdata_prefix) and \ name[len(self.cdata_prefix):].isdigit(): index = int(name[len(self.cdata_prefix):]) content.append((index, value)) elif self.is_xmlns(name): continue elif self.attr_prefix and \ name.startswith(self.attr_prefix) and \ name != self.attr_prefix: attr_name = name[len(self.attr_prefix):] ns_name = self.unmap_qname(attr_name, xsd_element.attributes) attributes[ns_name] = value elif not isinstance(value, MutableSequence) or not value: ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value)) content.append((ns_name, value)) elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value[0])) content.extend((ns_name, item) for item in value) else: ns_name = self.unmap_qname(name) xsd_child = xsd_element.match_child(ns_name) if xsd_child is not None: if xsd_child.type and xsd_child.type.is_list(): content.append((ns_name, value)) else: content.extend((ns_name, item) for item in value) elif self.attr_prefix == '' and ns_name in xsd_element.attributes: attributes[ns_name] = value else: content.extend((ns_name, item) for item in value) return ElementData(xsd_element.name, text, content, attributes, xmlns)
(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> xmlschema.converters.default.ElementData
713,651
xmlschema.validators.exceptions
XMLSchemaDecodeError
Raised when an XML data string is not decodable to a Python object. :param validator: the XSD validator. :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.
class XMLSchemaDecodeError(XMLSchemaValidationError): """ Raised when an XML data string is not decodable to a Python object. :param validator: the XSD validator. :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. """ message = "failed decoding {!r} with {!r}.\n" def __init__(self, validator: Union['XsdValidator', Callable[[Any], None]], obj: Any, decoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: super().__init__(validator, obj, reason, source, namespaces) self.decoder = decoder
(validator: Union[ForwardRef('XsdValidator'), Callable[[Any], NoneType]], obj: Any, decoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,652
xmlschema.validators.exceptions
__init__
null
def __init__(self, validator: Union['XsdValidator', Callable[[Any], None]], obj: Any, decoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: super().__init__(validator, obj, reason, source, namespaces) self.decoder = decoder
(self, validator: Union[ForwardRef('XsdValidator'), Callable[[Any], NoneType]], obj: Any, decoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,658
xmlschema.validators.exceptions
XMLSchemaEncodeError
Raised when an object is not encodable to an XML data string. :param validator: the XSD validator. :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.
class XMLSchemaEncodeError(XMLSchemaValidationError): """ Raised when an object is not encodable to an XML data string. :param validator: the XSD validator. :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. """ message = "failed encoding {!r} with {!r}.\n" def __init__(self, validator: Union['XsdValidator', Callable[[Any], None]], obj: Any, encoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: super().__init__(validator, obj, reason, source, namespaces) self.encoder = encoder
(validator: Union[ForwardRef('XsdValidator'), Callable[[Any], NoneType]], obj: Any, encoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,659
xmlschema.validators.exceptions
__init__
null
def __init__(self, validator: Union['XsdValidator', Callable[[Any], None]], obj: Any, encoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: super().__init__(validator, obj, reason, source, namespaces) self.encoder = encoder
(self, validator: Union[ForwardRef('XsdValidator'), Callable[[Any], NoneType]], obj: Any, encoder: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,665
xmlschema.exceptions
XMLSchemaException
The base exception that let you catch all the errors generated by the library.
class XMLSchemaException(Exception): """The base exception that let you catch all the errors generated by the library."""
null
713,666
xmlschema.validators.exceptions
XMLSchemaImportWarning
A schema namespace import fails.
class XMLSchemaImportWarning(XMLSchemaWarning): """A schema namespace import fails."""
null
713,667
xmlschema.validators.exceptions
XMLSchemaIncludeWarning
A schema include fails.
class XMLSchemaIncludeWarning(XMLSchemaWarning): """A schema include fails."""
null
713,668
xmlschema.validators.exceptions
XMLSchemaModelDepthError
Raised when recursion depth is exceeded while iterating a model group.
class XMLSchemaModelDepthError(XMLSchemaModelError): """Raised when recursion depth is exceeded while iterating a model group.""" def __init__(self, group: 'XsdGroup') -> None: msg = f"maximum model recursion depth exceeded while iterating {group!r}" super().__init__(group, message=msg)
(group: 'XsdGroup') -> None
713,669
xmlschema.validators.exceptions
__init__
null
def __init__(self, group: 'XsdGroup') -> None: msg = f"maximum model recursion depth exceeded while iterating {group!r}" super().__init__(group, message=msg)
(self, group: 'XsdGroup') -> None
713,671
xmlschema.validators.exceptions
__str__
null
def __str__(self) -> str: chunks = ['%s:\n' % self.message] if self.elem is not None: elem_as_string = cast( str, etree_tostring(self.elem, self.namespaces, ' ', 20) ) chunks.append("Schema component:\n\n%s\n" % elem_as_string) path = self.path if path is not None: chunks.append("Path: %s\n" % path) if self.schema_url is not None: chunks.append("Schema URL: %s\n" % self.schema_url) if self.origin_url not in (None, self.schema_url): chunks.append("Origin URL: %s\n" % self.origin_url) return '\n'.join(chunks) if len(chunks) > 1 else chunks[0][:-2]
(self) -> str
713,673
xmlschema.validators.exceptions
XMLSchemaModelError
Raised when a model error is found during the checking of a model group. :param group: the XSD model group. :param message: the error message.
class XMLSchemaModelError(XMLSchemaValidatorError, ValueError): """ Raised when a model error is found during the checking of a model group. :param group: the XSD model group. :param message: the error message. """ def __init__(self, group: 'XsdGroup', message: str) -> None: super().__init__( validator=group, message=message, elem=getattr(group, 'elem', None), source=getattr(group, 'source', None), namespaces=getattr(group, 'namespaces', None) )
(group: 'XsdGroup', message: str) -> None
713,674
xmlschema.validators.exceptions
__init__
null
def __init__(self, group: 'XsdGroup', message: str) -> None: super().__init__( validator=group, message=message, elem=getattr(group, 'elem', None), source=getattr(group, 'source', None), namespaces=getattr(group, 'namespaces', None) )
(self, group: 'XsdGroup', message: str) -> None
713,678
xmlschema.exceptions
XMLSchemaNamespaceError
Raised when a wrong runtime condition is found with a namespace.
class XMLSchemaNamespaceError(XMLSchemaException, RuntimeError): """Raised when a wrong runtime condition is found with a namespace."""
null
713,679
xmlschema.validators.exceptions
XMLSchemaNotBuiltError
Raised when there is an improper usage attempt of a not built XSD validator. :param validator: the XSD validator. :param message: the error message.
class XMLSchemaNotBuiltError(XMLSchemaValidatorError, RuntimeError): """ Raised when there is an improper usage attempt of a not built XSD validator. :param validator: the XSD validator. :param message: the error message. """ def __init__(self, validator: 'XsdValidator', message: str) -> None: super().__init__( validator=validator, message=message, elem=getattr(validator, 'elem', None), source=getattr(validator, 'source', None), namespaces=getattr(validator, 'namespaces', None) )
(validator: 'XsdValidator', message: str) -> None
713,680
xmlschema.validators.exceptions
__init__
null
def __init__(self, validator: 'XsdValidator', message: str) -> None: super().__init__( validator=validator, message=message, elem=getattr(validator, 'elem', None), source=getattr(validator, 'source', None), namespaces=getattr(validator, 'namespaces', None) )
(self, validator: 'XsdValidator', message: str) -> None
713,684
xmlschema.validators.exceptions
XMLSchemaParseError
Raised when an error is found during the building of an XSD validator. :param validator: the XSD validator. :param message: the error message. :param elem: the element that contains the error.
class XMLSchemaParseError(XMLSchemaValidatorError, SyntaxError): # type: ignore[misc] """ Raised when an error is found during the building of an XSD validator. :param validator: the XSD validator. :param message: the error message. :param elem: the element that contains the error. """ def __init__(self, validator: 'XsdValidator', message: str, elem: Optional[ElementType] = None) -> None: super().__init__( validator=validator, message=message, elem=elem if elem is not None else getattr(validator, 'elem', None), source=getattr(validator, 'source', None), namespaces=getattr(validator, 'namespaces', None), )
(validator: 'XsdValidator', message: str, elem: Optional[~T] = None) -> None
713,685
xmlschema.validators.exceptions
__init__
null
def __init__(self, validator: 'XsdValidator', message: str, elem: Optional[ElementType] = None) -> None: super().__init__( validator=validator, message=message, elem=elem if elem is not None else getattr(validator, 'elem', None), source=getattr(validator, 'source', None), namespaces=getattr(validator, 'namespaces', None), )
(self, validator: 'XsdValidator', message: str, elem: Optional[~T] = None) -> None
713,689
xmlschema.validators.exceptions
XMLSchemaStopValidation
Stops the validation process.
class XMLSchemaStopValidation(XMLSchemaException): """Stops the validation process."""
null
713,690
xmlschema.validators.exceptions
XMLSchemaTypeTableWarning
Not equivalent type table found in model.
class XMLSchemaTypeTableWarning(XMLSchemaWarning): """Not equivalent type table found in model."""
null
713,691
xmlschema.validators.exceptions
XMLSchemaValidationError
Raised when the XML data is not validated with the XSD component or schema. It's used by decoding and encoding methods. Encoding validation errors do not include XML data element and source, so the error is limited to a message containing object representation and a reason. :param validator: the XSD validator. :param obj: the not validated XML data. :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.
class XMLSchemaValidationError(XMLSchemaValidatorError, ValueError): """ Raised when the XML data is not validated with the XSD component or schema. It's used by decoding and encoding methods. Encoding validation errors do not include XML data element and source, so the error is limited to a message containing object representation and a reason. :param validator: the XSD validator. :param obj: the not validated XML data. :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. """ def __init__(self, validator: ValidatorType, obj: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: if isinstance(obj, str): obj_repr = repr(obj.encode('ascii', 'xmlcharrefreplace').decode('utf-8')) else: obj_repr = repr(obj) if len(obj_repr) > 200: obj_repr = f"{type(obj)} instance" super().__init__( validator=validator, message=f"failed validating {obj_repr} with {validator!r}", elem=obj if is_etree_element(obj) else None, source=source, namespaces=namespaces, ) self.obj = obj self.reason = reason def __repr__(self) -> str: return '%s(reason=%r)' % (self.__class__.__name__, self.reason) def __str__(self) -> str: chunks = ['%s:\n' % self.message] if self.reason is not None: chunks.append('Reason: %s\n' % self.reason) if hasattr(self.validator, 'tostring'): component_as_string = self.validator.tostring(' ', 20) chunks.append("Schema component:\n\n%s\n" % component_as_string) if is_etree_element(self.elem): chunks.append(f"Instance type: {type(self.elem)}\n") instance_as_string = self.get_elem_as_string(indent=' ', max_lines=20) else: chunks.append(f"Instance type: {type(self.obj)}\n") instance_as_string = self.get_obj_as_string(indent=' ', max_lines=20) if hasattr(self.elem, 'sourceline'): line = getattr(self.elem, 'sourceline') chunks.append(f"Instance (line {line!r}):\n\n{instance_as_string}\n") else: chunks.append(f"Instance:\n\n{instance_as_string}\n") if self.path is not None: chunks.append("Path: %s\n" % self.path) return '\n'.join(chunks) if len(chunks) > 1 else chunks[0][:-2] def get_obj_as_string(self, indent: str = '', max_lines: Optional[int] = None) -> str: """ Return a string representation of obj attribute, with optional indentation and an optional limit on lines. """ if is_etree_element(self.obj): return self.get_elem_as_string(indent, max_lines) pp = PrettyPrinter(indent=2, depth=6) obj_as_string = pp.pformat(self.obj) if indent: obj_as_string = textwrap.indent(obj_as_string, prefix=indent) if max_lines and len(obj_as_string.splitlines()) > max_lines: obj_as_string = '\n'.join(obj_as_string.splitlines()[:max_lines - 3]) obj_as_string += f'\n\n{indent}...\n{indent}...' return obj_as_string
(validator: Union[ForwardRef('XsdValidator'), Callable[[Any], NoneType]], obj: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,692
xmlschema.validators.exceptions
__init__
null
def __init__(self, validator: ValidatorType, obj: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: if isinstance(obj, str): obj_repr = repr(obj.encode('ascii', 'xmlcharrefreplace').decode('utf-8')) else: obj_repr = repr(obj) if len(obj_repr) > 200: obj_repr = f"{type(obj)} instance" super().__init__( validator=validator, message=f"failed validating {obj_repr} with {validator!r}", elem=obj if is_etree_element(obj) else None, source=source, namespaces=namespaces, ) self.obj = obj self.reason = reason
(self, validator: Union[ForwardRef('XsdValidator'), Callable[[Any], NoneType]], obj: Any, reason: Optional[str] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,698
xmlschema.validators.exceptions
XMLSchemaValidatorError
Base class for XSD validator errors. :param validator: the XSD validator. :param message: the error message. :param elem: the element that contains the error. :param source: the XML resource or the decoded data that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI.
class XMLSchemaValidatorError(XMLSchemaException): """ Base class for XSD validator errors. :param validator: the XSD validator. :param message: the error message. :param elem: the element that contains the error. :param source: the XML resource or the decoded data that contains the error. :param namespaces: is an optional mapping from namespace prefix to URI. """ _path: Optional[str] # Optional dump of the execution stack that can be set in collected # validator errors for debugging purposes. stack_trace: Optional[str] = None def __init__(self, validator: ValidatorType, message: str, elem: Optional[ElementType] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: self._path = None self.validator = validator self.message = message[:-1] if message[-1] in ('.', ':') else message self.namespaces = namespaces self.source = source self.elem = elem def __str__(self) -> str: chunks = ['%s:\n' % self.message] if self.elem is not None: elem_as_string = cast( str, etree_tostring(self.elem, self.namespaces, ' ', 20) ) chunks.append("Schema component:\n\n%s\n" % elem_as_string) path = self.path if path is not None: chunks.append("Path: %s\n" % path) if self.schema_url is not None: chunks.append("Schema URL: %s\n" % self.schema_url) if self.origin_url not in (None, self.schema_url): chunks.append("Origin URL: %s\n" % self.origin_url) return '\n'.join(chunks) if len(chunks) > 1 else chunks[0][:-2] @property def msg(self) -> str: return self.__str__() def __setattr__(self, name: str, value: Any) -> None: if name == 'elem' and value is not None: if not is_etree_element(value): raise XMLSchemaValueError( "'elem' attribute requires an Element, not %r." % type(value) ) if isinstance(self.source, XMLResource): self._path = etree_getpath( elem=value, root=self.source.root, namespaces=self.namespaces, relative=False, add_position=True ) if self.source.is_lazy(): value = None # Don't save the element of a lazy resource super().__setattr__(name, value) @property def sourceline(self) -> Any: """XML element *sourceline* if available (lxml Element) and *elem* is set.""" return getattr(self.elem, 'sourceline', None) @property def root(self) -> Optional[ElementType]: """The XML resource root element if *source* is set.""" if isinstance(self.source, XMLResource): return self.source.root else: return None @property def schema_url(self) -> Optional[str]: """The schema URL, if available and the *validator* is an XSD component.""" url: Optional[str] try: url = self.validator.schema.source.url # type: ignore[union-attr] except AttributeError: return getattr(self.validator, 'url', None) # it's the schema else: return url @property def origin_url(self) -> Optional[str]: """The origin schema URL, if available and the *validator* is an XSD component.""" url: Optional[str] try: url = self.validator.maps.validator.source.url # type: ignore[union-attr] except AttributeError: return None else: return url @property def path(self) -> Optional[str]: """The XPath of the element, if it's not `None` and the XML resource is set.""" if self.elem is None or not isinstance(self.source, XMLResource): return self._path return etree_getpath( elem=self.elem, root=self.source.root, namespaces=self.namespaces, relative=False, add_position=True ) def get_elem_as_string(self, indent: str = '', max_lines: Optional[int] = None) -> str: """Returns a string representation of elem attribute.""" kwargs = { 'elem': self.elem, 'namespaces': self.namespaces, 'indent': indent, 'max_lines': max_lines } try: return cast(str, etree_tostring(**kwargs)) # type: ignore[arg-type] except (ValueError, TypeError): return indent + repr(self.elem)
(validator: Union[ForwardRef('XsdValidator'), Callable[[Any], NoneType]], message: str, elem: Optional[~T] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,699
xmlschema.validators.exceptions
__init__
null
def __init__(self, validator: ValidatorType, message: str, elem: Optional[ElementType] = None, source: Optional[Any] = None, namespaces: Optional[NamespacesType] = None) -> None: self._path = None self.validator = validator self.message = message[:-1] if message[-1] in ('.', ':') else message self.namespaces = namespaces self.source = source self.elem = elem
(self, validator: Union[ForwardRef('XsdValidator'), Callable[[Any], NoneType]], message: str, elem: Optional[~T] = None, source: Optional[Any] = None, namespaces: Optional[~T] = None) -> None
713,703
xmlschema.documents
XmlDocument
An XML document bound with its schema. If no schema is get from the provided context and validation argument is 'skip' the XML document is associated with a generic schema, otherwise a ValueError is raised. :param source: a string containing XML data or a file path or a URL or a file like object or an ElementTree or an Element. :param schema: can be a :class:`xmlschema.XMLSchema` instance or a file-like object or a file path or a URL of a resource or a string containing the XSD schema. :param cls: class to use for building the schema instance (for default :class:`XMLSchema10` is used). :param validation: the XSD validation mode to use for validating the XML document, that can be 'strict' (default), 'lax' or 'skip'. :param namespaces: is an optional mapping from namespace prefix to URI. :param locations: resource location hints, that can be a dictionary or a sequence of couples (namespace URI, resource URL). :param base_url: the base URL for base :class:`xmlschema.XMLResource` initialization. :param allow: the security mode for base :class:`xmlschema.XMLResource` initialization. :param defuse: the defuse mode for base :class:`xmlschema.XMLResource` initialization. :param timeout: the timeout for base :class:`xmlschema.XMLResource` initialization. :param lazy: the lazy mode for base :class:`xmlschema.XMLResource` initialization. :param thin_lazy: the thin_lazy option for base :class:`xmlschema.XMLResource` initialization. :param uri_mapper: an optional argument for building the schema from location hints. :param use_location_hints: for default, in case a schema instance has to be built, uses also schema locations hints provided within XML data. Set this option to `False` to ignore these schema location hints.
class XmlDocument(XMLResource): """ An XML document bound with its schema. If no schema is get from the provided context and validation argument is 'skip' the XML document is associated with a generic schema, otherwise a ValueError is raised. :param source: a string containing XML data or a file path or a URL or a \ file like object or an ElementTree or an Element. :param schema: can be a :class:`xmlschema.XMLSchema` instance or a file-like \ object or a file path or a URL of a resource or a string containing the XSD schema. :param cls: class to use for building the schema instance (for default \ :class:`XMLSchema10` is used). :param validation: the XSD validation mode to use for validating the XML document, \ that can be 'strict' (default), 'lax' or 'skip'. :param namespaces: is an optional mapping from namespace prefix to URI. :param locations: resource location hints, that can be a dictionary or a \ sequence of couples (namespace URI, resource URL). :param base_url: the base URL for base :class:`xmlschema.XMLResource` initialization. :param allow: the security mode for base :class:`xmlschema.XMLResource` initialization. :param defuse: the defuse mode for base :class:`xmlschema.XMLResource` initialization. :param timeout: the timeout for base :class:`xmlschema.XMLResource` initialization. :param lazy: the lazy mode for base :class:`xmlschema.XMLResource` initialization. :param thin_lazy: the thin_lazy option for base :class:`xmlschema.XMLResource` \ initialization. :param uri_mapper: an optional argument for building the schema from location hints. :param use_location_hints: for default, in case a schema instance has \ to be built, uses also schema locations hints provided within XML data. \ Set this option to `False` to ignore these schema location hints. """ schema: Optional[XMLSchemaBase] = None _fallback_schema: Optional[XMLSchemaBase] = None validation: str = 'skip' namespaces: Optional[NamespacesType] = None errors: Union[Tuple[()], List[XMLSchemaValidationError]] = () def __init__(self, source: XMLSourceType, schema: Optional[Union[XMLSchemaBase, SchemaSourceType]] = None, cls: Optional[Type[XMLSchemaBase]] = None, validation: str = 'strict', namespaces: Optional[NamespacesType] = None, locations: Optional[LocationsType] = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, lazy: LazyType = False, thin_lazy: bool = True, uri_mapper: Optional[UriMapperType] = None, use_location_hints: bool = True) -> None: if cls is None: cls = XMLSchema10 self.validation = validation self._namespaces = get_namespace_map(namespaces) super().__init__(source, base_url, allow, defuse, timeout, lazy, thin_lazy) if isinstance(schema, XMLSchemaBase) and self.namespace in schema.maps.namespaces: self.schema = schema elif schema is not None and not isinstance(schema, XMLSchemaBase): self.schema = cls( source=schema, locations=locations, base_url=base_url, allow=allow, defuse=defuse, timeout=timeout, uri_mapper=uri_mapper ) else: if use_location_hints: try: schema_location, locations = fetch_schema_locations( source=self, locations=locations, base_url=base_url, uri_mapper=uri_mapper, root_only=False ) except ValueError: pass else: self.schema = cls( source=schema_location, locations=locations, allow=allow, defuse=defuse, timeout=timeout, uri_mapper=uri_mapper ) if self.schema is None: if XSI_TYPE in self._root.attrib: self.schema = get_dummy_schema(self._root.tag, cls) elif validation != 'skip': msg = "cannot get a schema for XML data, provide a schema argument" raise XMLSchemaValueError(msg) else: self._fallback_schema = get_dummy_schema(self._root.tag, cls) if self.schema is None: pass elif validation == 'strict': self.schema.validate(self, namespaces=self.namespaces) elif validation == 'lax': self.errors = [e for e in self.schema.iter_errors(self, namespaces=self.namespaces)] elif validation != 'skip': raise XMLSchemaValueError("%r is not a validation mode" % validation) def parse(self, source: XMLSourceType, lazy: LazyType = False) -> None: super().parse(source, lazy) self.namespaces = self.get_namespaces(root_only=True) if self.schema is None: pass elif self.validation == 'strict': self.schema.validate(self, namespaces=self.namespaces) elif self.validation == 'lax': self.errors = [e for e in self.schema.iter_errors(self, namespaces=self.namespaces)] def get_namespaces(self, namespaces: Optional[NamespacesType] = None, root_only: bool = True) -> NamespacesType: namespaces = get_namespace_map(namespaces) update_namespaces(namespaces, self._namespaces.items(), root_declarations=True) return super().get_namespaces(namespaces, root_only) def getroot(self) -> ElementType: """Get the root element of the XML document.""" return self._root def get_etree_document(self) -> Any: """ The resource as ElementTree XML document. If the resource is lazy raises a resource error. """ if is_etree_document(self._source): return self._source elif self._lazy: raise XMLResourceError( "cannot create an ElementTree instance from a lazy XML resource" ) elif hasattr(self._root, 'nsmap'): return self._root.getroottree() # type: ignore[attr-defined] else: return ElementTree.ElementTree(self._root) def decode(self, **kwargs: Any) -> DecodeType[Any]: """ Decode the XML document to a nested Python dictionary. :param kwargs: options for the decode/to_dict method of the schema instance. """ if 'validation' not in kwargs: kwargs['validation'] = self.validation if 'namespaces' not in kwargs: kwargs['namespaces'] = self.namespaces schema = self.schema or self._fallback_schema if schema is None: return None obj = schema.to_dict(self, **kwargs) return obj[0] if isinstance(obj, tuple) else obj def to_json(self, fp: Optional[IO[str]] = None, json_options: Optional[Dict[str, Any]] = None, **kwargs: Any) -> JsonDecodeType: """ Converts loaded XML data to a JSON string or file. :param fp: can be a :meth:`write()` supporting file-like object. :param json_options: a dictionary with options for the JSON deserializer. :param kwargs: options for the decode/to_dict method of the schema instance. """ if json_options is None: json_options = {} path = kwargs.pop('path', None) if 'validation' not in kwargs: kwargs['validation'] = self.validation if 'namespaces' not in kwargs: kwargs['namespaces'] = self.namespaces if 'decimal_type' not in kwargs: kwargs['decimal_type'] = float errors: List[XMLSchemaValidationError] = [] if path is None and self._lazy and 'cls' not in json_options: json_options['cls'] = get_lazy_json_encoder(errors) kwargs['lazy_decode'] = True schema = self.schema or self._fallback_schema if schema is not None: obj = schema.decode(self, path=path, **kwargs) else: obj = None if isinstance(obj, tuple): if fp is not None: json.dump(obj[0], fp, **json_options) obj[1].extend(errors) return tuple(obj[1]) else: result = json.dumps(obj[0], **json_options) obj[1].extend(errors) return result, tuple(obj[1]) elif fp is not None: json.dump(obj, fp, **json_options) return None if not errors else tuple(errors) else: result = json.dumps(obj, **json_options) return result if not errors else (result, tuple(errors)) def write(self, file: Union[str, TextIO, BinaryIO], encoding: str = 'us-ascii', xml_declaration: bool = False, default_namespace: Optional[str] = None, method: str = "xml") -> None: """Serialize an XML resource to a file. Cannot be used with lazy resources.""" if self._lazy: raise XMLResourceError("cannot serialize a lazy XML resource") kwargs: Dict[str, Any] = { 'xml_declaration': xml_declaration, 'encoding': encoding, 'method': method, } if not default_namespace: kwargs['namespaces'] = self.namespaces else: namespaces: Optional[Dict[Optional[str], str]] if self.namespaces is None: namespaces = {} else: namespaces = {k: v for k, v in self.namespaces.items()} if hasattr(self._root, 'nsmap'): # noinspection PyTypeChecker namespaces[None] = default_namespace else: namespaces[''] = default_namespace kwargs['namespaces'] = namespaces _string = etree_tostring(self._root, **kwargs) if isinstance(file, str): if isinstance(_string, str): with open(file, 'w', encoding='utf-8') as fp: fp.write(_string) else: with open(file, 'wb') as _fp: _fp.write(_string) elif isinstance(file, TextIOBase): if isinstance(_string, bytes): file.write(_string.decode('utf-8')) else: file.write(_string) elif isinstance(file, IOBase): if isinstance(_string, str): file.write(_string.encode('utf-8')) else: file.write(_string) else: msg = "unexpected type %r for 'file' argument" raise XMLSchemaTypeError(msg % type(file))
(source: Optional[~T], schema: Optional[xmlschema.validators.schemas.XMLSchemaBase] = None, cls: Optional[Type[xmlschema.validators.schemas.XMLSchemaBase]] = None, validation: str = 'strict', namespaces: Optional[~T] = None, locations: Optional[~T] = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, lazy: Optional[~T] = False, thin_lazy: bool = True, uri_mapper: Optional[~T] = None, use_location_hints: bool = True) -> None
713,704
xmlschema.documents
__init__
null
def __init__(self, source: XMLSourceType, schema: Optional[Union[XMLSchemaBase, SchemaSourceType]] = None, cls: Optional[Type[XMLSchemaBase]] = None, validation: str = 'strict', namespaces: Optional[NamespacesType] = None, locations: Optional[LocationsType] = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, lazy: LazyType = False, thin_lazy: bool = True, uri_mapper: Optional[UriMapperType] = None, use_location_hints: bool = True) -> None: if cls is None: cls = XMLSchema10 self.validation = validation self._namespaces = get_namespace_map(namespaces) super().__init__(source, base_url, allow, defuse, timeout, lazy, thin_lazy) if isinstance(schema, XMLSchemaBase) and self.namespace in schema.maps.namespaces: self.schema = schema elif schema is not None and not isinstance(schema, XMLSchemaBase): self.schema = cls( source=schema, locations=locations, base_url=base_url, allow=allow, defuse=defuse, timeout=timeout, uri_mapper=uri_mapper ) else: if use_location_hints: try: schema_location, locations = fetch_schema_locations( source=self, locations=locations, base_url=base_url, uri_mapper=uri_mapper, root_only=False ) except ValueError: pass else: self.schema = cls( source=schema_location, locations=locations, allow=allow, defuse=defuse, timeout=timeout, uri_mapper=uri_mapper ) if self.schema is None: if XSI_TYPE in self._root.attrib: self.schema = get_dummy_schema(self._root.tag, cls) elif validation != 'skip': msg = "cannot get a schema for XML data, provide a schema argument" raise XMLSchemaValueError(msg) else: self._fallback_schema = get_dummy_schema(self._root.tag, cls) if self.schema is None: pass elif validation == 'strict': self.schema.validate(self, namespaces=self.namespaces) elif validation == 'lax': self.errors = [e for e in self.schema.iter_errors(self, namespaces=self.namespaces)] elif validation != 'skip': raise XMLSchemaValueError("%r is not a validation mode" % validation)
(self, source: Optional[~T], schema: Union[xmlschema.validators.schemas.XMLSchemaBase, ~T, NoneType] = None, cls: Optional[Type[xmlschema.validators.schemas.XMLSchemaBase]] = None, validation: str = 'strict', namespaces: Optional[~T] = None, locations: Optional[~T] = None, base_url: Optional[str] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, lazy: Optional[~T] = False, thin_lazy: bool = True, uri_mapper: Optional[~T] = None, use_location_hints: bool = True) -> NoneType
713,714
xmlschema.documents
decode
Decode the XML document to a nested Python dictionary. :param kwargs: options for the decode/to_dict method of the schema instance.
def decode(self, **kwargs: Any) -> DecodeType[Any]: """ Decode the XML document to a nested Python dictionary. :param kwargs: options for the decode/to_dict method of the schema instance. """ if 'validation' not in kwargs: kwargs['validation'] = self.validation if 'namespaces' not in kwargs: kwargs['namespaces'] = self.namespaces schema = self.schema or self._fallback_schema if schema is None: return None obj = schema.to_dict(self, **kwargs) return obj[0] if isinstance(obj, tuple) else obj
(self, **kwargs: Any) -> Optional[Any]
713,718
xmlschema.documents
get_etree_document
The resource as ElementTree XML document. If the resource is lazy raises a resource error.
def get_etree_document(self) -> Any: """ The resource as ElementTree XML document. If the resource is lazy raises a resource error. """ if is_etree_document(self._source): return self._source elif self._lazy: raise XMLResourceError( "cannot create an ElementTree instance from a lazy XML resource" ) elif hasattr(self._root, 'nsmap'): return self._root.getroottree() # type: ignore[attr-defined] else: return ElementTree.ElementTree(self._root)
(self) -> Any
713,720
xmlschema.documents
get_namespaces
null
def get_namespaces(self, namespaces: Optional[NamespacesType] = None, root_only: bool = True) -> NamespacesType: namespaces = get_namespace_map(namespaces) update_namespaces(namespaces, self._namespaces.items(), root_declarations=True) return super().get_namespaces(namespaces, root_only)
(self, namespaces: Optional[~T] = None, root_only: bool = True) -> Optional[~T]
713,725
xmlschema.documents
getroot
Get the root element of the XML document.
def getroot(self) -> ElementType: """Get the root element of the XML document.""" return self._root
(self) -> Optional[~T]
713,737
xmlschema.documents
parse
null
def parse(self, source: XMLSourceType, lazy: LazyType = False) -> None: super().parse(source, lazy) self.namespaces = self.get_namespaces(root_only=True) if self.schema is None: pass elif self.validation == 'strict': self.schema.validate(self, namespaces=self.namespaces) elif self.validation == 'lax': self.errors = [e for e in self.schema.iter_errors(self, namespaces=self.namespaces)]
(self, source: Optional[~T], lazy: Optional[~T] = False) -> NoneType
713,740
xmlschema.documents
to_json
Converts loaded XML data to a JSON string or file. :param fp: can be a :meth:`write()` supporting file-like object. :param json_options: a dictionary with options for the JSON deserializer. :param kwargs: options for the decode/to_dict method of the schema instance.
def to_json(self, fp: Optional[IO[str]] = None, json_options: Optional[Dict[str, Any]] = None, **kwargs: Any) -> JsonDecodeType: """ Converts loaded XML data to a JSON string or file. :param fp: can be a :meth:`write()` supporting file-like object. :param json_options: a dictionary with options for the JSON deserializer. :param kwargs: options for the decode/to_dict method of the schema instance. """ if json_options is None: json_options = {} path = kwargs.pop('path', None) if 'validation' not in kwargs: kwargs['validation'] = self.validation if 'namespaces' not in kwargs: kwargs['namespaces'] = self.namespaces if 'decimal_type' not in kwargs: kwargs['decimal_type'] = float errors: List[XMLSchemaValidationError] = [] if path is None and self._lazy and 'cls' not in json_options: json_options['cls'] = get_lazy_json_encoder(errors) kwargs['lazy_decode'] = True schema = self.schema or self._fallback_schema if schema is not None: obj = schema.decode(self, path=path, **kwargs) else: obj = None if isinstance(obj, tuple): if fp is not None: json.dump(obj[0], fp, **json_options) obj[1].extend(errors) return tuple(obj[1]) else: result = json.dumps(obj[0], **json_options) obj[1].extend(errors) return result, tuple(obj[1]) elif fp is not None: json.dump(obj, fp, **json_options) return None if not errors else tuple(errors) else: result = json.dumps(obj, **json_options) return result if not errors else (result, tuple(errors))
(self, fp: Optional[IO[str]] = None, json_options: Optional[Dict[str, Any]] = None, **kwargs: Any) -> Optional[~T]
713,742
xmlschema.documents
write
Serialize an XML resource to a file. Cannot be used with lazy resources.
def write(self, file: Union[str, TextIO, BinaryIO], encoding: str = 'us-ascii', xml_declaration: bool = False, default_namespace: Optional[str] = None, method: str = "xml") -> None: """Serialize an XML resource to a file. Cannot be used with lazy resources.""" if self._lazy: raise XMLResourceError("cannot serialize a lazy XML resource") kwargs: Dict[str, Any] = { 'xml_declaration': xml_declaration, 'encoding': encoding, 'method': method, } if not default_namespace: kwargs['namespaces'] = self.namespaces else: namespaces: Optional[Dict[Optional[str], str]] if self.namespaces is None: namespaces = {} else: namespaces = {k: v for k, v in self.namespaces.items()} if hasattr(self._root, 'nsmap'): # noinspection PyTypeChecker namespaces[None] = default_namespace else: namespaces[''] = default_namespace kwargs['namespaces'] = namespaces _string = etree_tostring(self._root, **kwargs) if isinstance(file, str): if isinstance(_string, str): with open(file, 'w', encoding='utf-8') as fp: fp.write(_string) else: with open(file, 'wb') as _fp: _fp.write(_string) elif isinstance(file, TextIOBase): if isinstance(_string, bytes): file.write(_string.decode('utf-8')) else: file.write(_string) elif isinstance(file, IOBase): if isinstance(_string, str): file.write(_string.encode('utf-8')) else: file.write(_string) else: msg = "unexpected type %r for 'file' argument" raise XMLSchemaTypeError(msg % type(file))
(self, file: Union[str, TextIO, BinaryIO], encoding: str = 'us-ascii', xml_declaration: bool = False, default_namespace: Optional[str] = None, method: str = 'xml') -> NoneType
713,743
xmlschema.validators.attributes
XsdAttribute
Class for XSD 1.0 *attribute* declarations. :ivar type: the XSD simpleType of the attribute. .. <attribute default = string fixed = string form = (qualified | unqualified) id = ID name = NCName ref = QName type = QName use = (optional | prohibited | required) : optional {any attributes with non-schema namespace ...}> Content: (annotation?, simpleType?) </attribute>
class XsdAttribute(XsdComponent, ValidationMixin[str, DecodedValueType]): """ Class for XSD 1.0 *attribute* declarations. :ivar type: the XSD simpleType of the attribute. .. <attribute default = string fixed = string form = (qualified | unqualified) id = ID name = NCName ref = QName type = QName use = (optional | prohibited | required) : optional {any attributes with non-schema namespace ...}> Content: (annotation?, simpleType?) </attribute> """ _ADMITTED_TAGS = {XSD_ATTRIBUTE} name: str local_name: str qualified_name: str prefixed_name: str type: XsdSimpleType copy: Callable[['XsdAttribute'], 'XsdAttribute'] qualified: bool = False default: Optional[str] = None fixed: Optional[str] = None form: Optional[str] = None use: str = 'optional' inheritable: bool = False # For XSD 1.1 attributes, always False for XSD 1.0 attributes. def _parse(self) -> None: attrib = self.elem.attrib if 'use' in attrib and self.parent is not None and \ attrib['use'] in {'optional', 'prohibited', 'required'}: self.use = attrib['use'] if self._parse_reference(): try: xsd_attribute = self.maps.lookup_attribute(self.name) except LookupError: self.type = self.any_simple_type msg = _("unknown attribute {!r}") self.parse_error(msg.format(self.name)) else: self.ref = xsd_attribute self.type = xsd_attribute.type self.qualified = xsd_attribute.qualified self.form = xsd_attribute.form if xsd_attribute.default is not None and 'default' not in attrib: self.default = xsd_attribute.default if xsd_attribute.fixed is not None: if 'fixed' not in attrib: self.fixed = xsd_attribute.fixed elif xsd_attribute.fixed != attrib['fixed']: msg = _("referenced attribute has a different fixed value {!r}") self.parse_error(msg.format(xsd_attribute.fixed)) for attribute in ('form', 'type'): if attribute in self.elem.attrib: msg = _("attribute {!r} is not allowed when attribute reference is used") self.parse_error(msg.format(attribute)) else: if 'form' in attrib: self.form = attrib['form'] if self.parent is not None and self.form == 'qualified': self.qualified = True elif self.schema.attribute_form_default == 'qualified': self.qualified = True try: name = attrib['name'] except KeyError: pass else: if name == 'xmlns': msg = _("an attribute name must be different from 'xmlns'") self.parse_error(msg) if self.parent is None or self.qualified: if self.target_namespace == XSI_NAMESPACE and \ name not in ('nil', 'type', 'schemaLocation', 'noNamespaceSchemaLocation'): msg = _("cannot add attributes in %r namespace") self.parse_error(msg % XSI_NAMESPACE) self.name = get_qname(self.target_namespace, name) else: self.name = name child = self._parse_child_component(self.elem) if 'type' in attrib: try: type_qname = self.schema.resolve_qname(attrib['type']) except (KeyError, ValueError, RuntimeError) as err: self.type = self.any_simple_type self.parse_error(err) else: try: self.type = cast(XsdSimpleType, self.maps.lookup_type(type_qname)) except LookupError as err: self.type = self.any_simple_type self.parse_error(err) if child is not None and child.tag == XSD_SIMPLE_TYPE: msg = _("ambiguous type definition for XSD attribute") self.parse_error(msg) elif child is not None: # No 'type' attribute in declaration, parse for child local simpleType self.type = self.schema.simple_type_factory(child, self.schema, self) else: # Empty declaration means xsdAnySimpleType self.type = self.any_simple_type if not isinstance(self.type, XsdSimpleType): self.type = self.any_simple_type msg = _("XSD attribute's type must be a simpleType") self.parse_error(msg) # Check value constraints if 'default' in attrib: self.default = attrib['default'] if 'fixed' in attrib: msg = _("'default' and 'fixed' attributes are mutually exclusive") self.parse_error(msg) if self.use != 'optional': msg = _("the attribute 'use' must be 'optional' " "if the attribute 'default' is present") self.parse_error(msg) if not self.type.is_valid(self.default): msg = _("default value {!r} is not compatible with attribute's type") self.parse_error(msg.format(self.default)) elif self.type.is_key() and self.xsd_version == '1.0': msg = _("xs:ID key attributes cannot have a default value") self.parse_error(msg) elif 'fixed' in attrib: self.fixed = attrib['fixed'] if not self.type.is_valid(self.fixed): msg = _("fixed value {!r} is not compatible with attribute's type") self.parse_error(msg.format(self.fixed)) elif self.type.is_key() and self.xsd_version == '1.0': msg = _("xs:ID key attributes cannot have a fixed value") self.parse_error(msg) @property def built(self) -> bool: return True @property def validation_attempted(self) -> str: return 'full' @property def scope(self) -> str: """The scope of the attribute declaration that can be 'global' or 'local'.""" return 'global' if self.parent is None else 'local' @property def value_constraint(self) -> Optional[str]: """The fixed or the default value if either is defined, `None` otherwise.""" return self.fixed if self.fixed is not None else self.default def is_optional(self) -> bool: return self.use == 'optional' def is_required(self) -> bool: return self.use == 'required' def is_prohibited(self) -> bool: return self.use == 'prohibited' def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[XsdComponent]: if xsd_classes is None or isinstance(self, xsd_classes): yield self if self.ref is None and self.type.parent is not None: yield from self.type.iter_components(xsd_classes) def data_value(self, text: str) -> AtomicValueType: """Returns the decoded data value of the provided text as XPath fn:data().""" return cast(AtomicValueType, self.decode(text, validation='skip')) def iter_decode(self, obj: str, validation: str = 'lax', **kwargs: Any) \ -> IterDecodeType[DecodedValueType]: if obj is None and self.default is not None: obj = self.default if self.type.is_notation(): if self.type.name == XSD_NOTATION_TYPE: msg = _("cannot validate against xs:NOTATION directly, " "only against a subtype with an enumeration facet") yield self.validation_error(validation, msg, obj, **kwargs) elif not self.type.enumeration: msg = _("missing enumeration facet in xs:NOTATION subtype") yield self.validation_error(validation, msg, obj, **kwargs) if self.fixed is not None: if obj is None: obj = self.fixed elif obj != self.fixed and \ self.type.text_decode(obj) != self.type.text_decode(self.fixed): msg = _("attribute {0!r} has a fixed value {1!r}").format(self.name, self.fixed) yield self.validation_error(validation, msg, obj, **kwargs) for value in self.type.iter_decode(obj, validation, **kwargs): if isinstance(value, XMLSchemaValidationError): value.reason = _('attribute {0}={1!r}: {2}').format( self.prefixed_name, obj, value.reason ) yield value continue elif 'value_hook' in kwargs: yield kwargs['value_hook'](value, self.type) elif isinstance(value, (int, float, list)) or value is None: yield value elif isinstance(value, str): if value.startswith('{') and self.type.is_qname(): yield obj else: yield value elif isinstance(value, Decimal): try: yield kwargs['decimal_type'](value) except (KeyError, TypeError): yield value elif isinstance(value, (AbstractDateTime, Duration)): yield value if kwargs.get('datetime_types') else obj.strip() elif isinstance(value, AbstractBinary) and not kwargs.get('binary_types'): yield str(value) else: yield value break # pragma: no cover def iter_encode(self, obj: Any, validation: str = 'lax', **kwargs: Any) \ -> IterEncodeType[Union[EncodedValueType]]: yield from self.type.iter_encode(obj, validation, **kwargs)
(elem: Optional[~T], schema: Optional[~T], parent: Optional[ForwardRef('XsdComponent')] = None, name: str = None) -> None
713,744
xmlschema.validators.xsdbase
copy
null
def copy(self) -> 'XsdValidator': validator: 'XsdValidator' = object.__new__(self.__class__) validator.__dict__.update(self.__dict__) validator.errors = self.errors[:] # shallow copy duplicates errors list return validator
(self) -> xmlschema.validators.xsdbase.XsdValidator
713,745
xmlschema.validators.xsdbase
__init__
null
def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional['XsdComponent'] = None, name: Optional[str] = None) -> None: super().__init__(schema.validation) if name: self.name = name if parent is not None: self.parent = parent self.schema = schema self.maps: XsdGlobals = schema.maps self.elem = elem
(self, elem: Optional[~T], schema: Optional[~T], parent: Optional[xmlschema.validators.xsdbase.XsdComponent] = None, name: Optional[str] = None) -> NoneType
713,746
xmlschema.validators.xsdbase
__repr__
null
def __repr__(self) -> str: if self.ref is not None: return '%s(ref=%r)' % (self.__class__.__name__, self.prefixed_name) else: return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name)
(self) -> str
713,747
xmlschema.validators.xsdbase
__setattr__
null
def __setattr__(self, name: str, value: Any) -> None: if name == 'elem': if value.tag not in self._ADMITTED_TAGS: msg = "wrong XSD element {!r} for {!r}, must be one of {!r}" raise XMLSchemaValueError( msg.format(value.tag, self.__class__, self._ADMITTED_TAGS) ) super().__setattr__(name, value) if self.errors: self.errors.clear() self._parse() else: super().__setattr__(name, value)
(self, name: str, value: Any) -> NoneType
713,748
xmlschema.validators.xsdbase
_get_converter
null
def _get_converter(self, obj: Any, kwargs: Dict[str, Any]) -> XMLSchemaConverter: if 'source' not in kwargs: if isinstance(obj, XMLResource): kwargs['source'] = obj elif is_etree_element(obj) or is_etree_document(obj): kwargs['source'] = XMLResource(obj) else: kwargs['source'] = obj converter = kwargs['converter'] = self.schema.get_converter(**kwargs) kwargs['namespaces'] = converter.namespaces return converter
(self, obj: Any, kwargs: Dict[str, Any]) -> xmlschema.converters.default.XMLSchemaConverter
713,749
xmlschema.validators.attributes
_parse
null
def _parse(self) -> None: attrib = self.elem.attrib if 'use' in attrib and self.parent is not None and \ attrib['use'] in {'optional', 'prohibited', 'required'}: self.use = attrib['use'] if self._parse_reference(): try: xsd_attribute = self.maps.lookup_attribute(self.name) except LookupError: self.type = self.any_simple_type msg = _("unknown attribute {!r}") self.parse_error(msg.format(self.name)) else: self.ref = xsd_attribute self.type = xsd_attribute.type self.qualified = xsd_attribute.qualified self.form = xsd_attribute.form if xsd_attribute.default is not None and 'default' not in attrib: self.default = xsd_attribute.default if xsd_attribute.fixed is not None: if 'fixed' not in attrib: self.fixed = xsd_attribute.fixed elif xsd_attribute.fixed != attrib['fixed']: msg = _("referenced attribute has a different fixed value {!r}") self.parse_error(msg.format(xsd_attribute.fixed)) for attribute in ('form', 'type'): if attribute in self.elem.attrib: msg = _("attribute {!r} is not allowed when attribute reference is used") self.parse_error(msg.format(attribute)) else: if 'form' in attrib: self.form = attrib['form'] if self.parent is not None and self.form == 'qualified': self.qualified = True elif self.schema.attribute_form_default == 'qualified': self.qualified = True try: name = attrib['name'] except KeyError: pass else: if name == 'xmlns': msg = _("an attribute name must be different from 'xmlns'") self.parse_error(msg) if self.parent is None or self.qualified: if self.target_namespace == XSI_NAMESPACE and \ name not in ('nil', 'type', 'schemaLocation', 'noNamespaceSchemaLocation'): msg = _("cannot add attributes in %r namespace") self.parse_error(msg % XSI_NAMESPACE) self.name = get_qname(self.target_namespace, name) else: self.name = name child = self._parse_child_component(self.elem) if 'type' in attrib: try: type_qname = self.schema.resolve_qname(attrib['type']) except (KeyError, ValueError, RuntimeError) as err: self.type = self.any_simple_type self.parse_error(err) else: try: self.type = cast(XsdSimpleType, self.maps.lookup_type(type_qname)) except LookupError as err: self.type = self.any_simple_type self.parse_error(err) if child is not None and child.tag == XSD_SIMPLE_TYPE: msg = _("ambiguous type definition for XSD attribute") self.parse_error(msg) elif child is not None: # No 'type' attribute in declaration, parse for child local simpleType self.type = self.schema.simple_type_factory(child, self.schema, self) else: # Empty declaration means xsdAnySimpleType self.type = self.any_simple_type if not isinstance(self.type, XsdSimpleType): self.type = self.any_simple_type msg = _("XSD attribute's type must be a simpleType") self.parse_error(msg) # Check value constraints if 'default' in attrib: self.default = attrib['default'] if 'fixed' in attrib: msg = _("'default' and 'fixed' attributes are mutually exclusive") self.parse_error(msg) if self.use != 'optional': msg = _("the attribute 'use' must be 'optional' " "if the attribute 'default' is present") self.parse_error(msg) if not self.type.is_valid(self.default): msg = _("default value {!r} is not compatible with attribute's type") self.parse_error(msg.format(self.default)) elif self.type.is_key() and self.xsd_version == '1.0': msg = _("xs:ID key attributes cannot have a default value") self.parse_error(msg) elif 'fixed' in attrib: self.fixed = attrib['fixed'] if not self.type.is_valid(self.fixed): msg = _("fixed value {!r} is not compatible with attribute's type") self.parse_error(msg.format(self.fixed)) elif self.type.is_key() and self.xsd_version == '1.0': msg = _("xs:ID key attributes cannot have a fixed value") self.parse_error(msg)
(self) -> NoneType
713,750
xmlschema.validators.xsdbase
_parse_child_component
null
def _parse_child_component(self, elem: ElementType, strict: bool = True) \ -> Optional[ElementType]: child = None for e in elem: if e.tag == XSD_ANNOTATION or callable(e.tag): continue elif not strict: return e elif child is not None: msg = _("too many XSD components, unexpected {0!r} found at position {1}") self.parse_error(msg.format(child, elem[:].index(e)), elem) break else: child = e return child
(self, elem: Optional[~T], strict: bool = True) -> Optional[~T]
713,751
xmlschema.validators.xsdbase
_parse_reference
Helper method for referable components. Returns `True` if a valid reference QName is found without any error, otherwise returns `None`. Sets an id-related name for the component ('nameless_<id of the instance>') if both the attributes 'ref' and 'name' are missing.
def _parse_reference(self) -> Optional[bool]: """ Helper method for referable components. Returns `True` if a valid reference QName is found without any error, otherwise returns `None`. Sets an id-related name for the component ('nameless_<id of the instance>') if both the attributes 'ref' and 'name' are missing. """ ref = self.elem.get('ref') if ref is None: if 'name' in self.elem.attrib: return None elif self.parent is None: msg = _("missing attribute 'name' in a global %r") self.parse_error(msg % type(self)) else: msg = _("missing both attributes 'name' and 'ref' in local %r") self.parse_error(msg % type(self)) elif 'name' in self.elem.attrib: msg = _("attributes 'name' and 'ref' are mutually exclusive") self.parse_error(msg) elif self.parent is None: msg = _("attribute 'ref' not allowed in a global %r") self.parse_error(msg % type(self)) else: try: self.name = self.schema.resolve_qname(ref) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) else: if self._parse_child_component(self.elem, strict=False) is not None: msg = _("a reference component cannot have child definitions/declarations") self.parse_error(msg) return True return None
(self) -> Optional[bool]
713,752
xmlschema.validators.xsdbase
_parse_target_namespace
XSD 1.1 targetNamespace attribute in elements and attributes declarations.
def _parse_target_namespace(self) -> None: """ XSD 1.1 targetNamespace attribute in elements and attributes declarations. """ if 'targetNamespace' not in self.elem.attrib: return self._target_namespace = self.elem.attrib['targetNamespace'].strip() if self._target_namespace == XMLNS_NAMESPACE: # https://www.w3.org/TR/xmlschema11-1/#sec-nss-special msg = _(f"The namespace {XMLNS_NAMESPACE} cannot be used as 'targetNamespace'") raise XMLSchemaValueError(msg) if 'name' not in self.elem.attrib: msg = _("attribute 'name' must be present when " "'targetNamespace' attribute is provided") self.parse_error(msg) if 'form' in self.elem.attrib: msg = _("attribute 'form' must be absent when " "'targetNamespace' attribute is provided") self.parse_error(msg) if self._target_namespace != self.schema.target_namespace: if self.parent is None: msg = _("a global %s must have the same namespace as its parent schema") self.parse_error(msg % self.__class__.__name__) xsd_type = self.get_parent_type() if xsd_type is None or xsd_type.parent is not None: pass elif xsd_type.derivation != 'restriction' or \ getattr(xsd_type.base_type, 'name', None) == XSD_ANY_TYPE: msg = _("a declaration contained in a global complexType " "must have the same namespace as its parent schema") self.parse_error(msg) if self.name is None: pass # pragma: no cover elif not self._target_namespace: self.name = local_name(self.name) else: self.name = f'{{{self._target_namespace}}}{local_name(self.name)}'
(self) -> NoneType
713,754
xmlschema.validators.xsdbase
build
Builds components that are not fully parsed at initialization, like model groups or internal local elements in model groups, otherwise does nothing.
def build(self) -> None: """ Builds components that are not fully parsed at initialization, like model groups or internal local elements in model groups, otherwise does nothing. """
(self) -> NoneType
713,756
xmlschema.validators.attributes
data_value
Returns the decoded data value of the provided text as XPath fn:data().
def data_value(self, text: str) -> AtomicValueType: """Returns the decoded data value of the provided text as XPath fn:data().""" return cast(AtomicValueType, self.decode(text, validation='skip'))
(self, text: str) -> Optional[~T]
713,757
xmlschema.validators.xsdbase
decode
Decodes XML data. :param obj: the XML data. Can be a string for an attribute or for simple type components or a dictionary for an attribute group or an ElementTree's Element for other components. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param kwargs: optional keyword arguments for the method :func:`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:`xmlschema.XMLSchemaValidationError` if the object is not decodable by the XSD component, or also if it's invalid when ``validation='strict'`` is provided.
def decode(self, obj: ST, validation: str = 'strict', **kwargs: Any) -> DecodeType[DT]: """ Decodes XML data. :param obj: the XML data. Can be a string for an attribute or for simple type \ components or a dictionary for an attribute group or an ElementTree's \ Element for other components. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param kwargs: optional keyword arguments for the method :func:`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:`xmlschema.XMLSchemaValidationError` if the object is not decodable by \ the XSD component, or also if it's invalid when ``validation='strict'`` is provided. """ check_validation_mode(validation) result: Union[DT, XMLSchemaValidationError] errors: List[XMLSchemaValidationError] = [] for result in self.iter_decode(obj, validation, **kwargs): # pragma: no cover if not isinstance(result, XMLSchemaValidationError): return (result, errors) if validation == 'lax' else result elif validation == 'strict': raise result else: errors.append(result) return (None, errors) if validation == 'lax' else None # fallback: pragma: no cover
(self, obj: ~ST, validation: str = 'strict', **kwargs: Any) -> Optional[~DT]
713,758
xmlschema.validators.xsdbase
encode
Encodes data to XML. :param obj: the data to be encoded to XML. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param kwargs: optional keyword arguments for the method :func:`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:`xmlschema.XMLSchemaValidationError` if the object is not encodable by the XSD component, or also if it's invalid when ``validation='strict'`` is provided.
def encode(self, obj: Any, validation: str = 'strict', **kwargs: Any) -> EncodeType[Any]: """ Encodes data to XML. :param obj: the data to be encoded to XML. :param validation: the validation mode. Can be 'lax', 'strict' or 'skip. :param kwargs: optional keyword arguments for the method :func:`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:`xmlschema.XMLSchemaValidationError` if the object is not encodable by \ the XSD component, or also if it's invalid when ``validation='strict'`` is provided. """ check_validation_mode(validation) result, errors = None, [] for result in self.iter_encode(obj, validation=validation, **kwargs): # pragma: no cover if not isinstance(result, XMLSchemaValidationError): break elif validation == 'strict': raise result else: errors.append(result) return (result, errors) if validation == 'lax' else result
(self, obj: Any, validation: str = 'strict', **kwargs: Any) -> Optional[Any]
713,759
xmlschema.validators.xsdbase
get_global
Returns the global XSD component that contains the component instance.
def get_global(self) -> 'XsdComponent': """Returns the global XSD component that contains the component instance.""" if self.parent is None: return self component = self.parent while component is not self: if component.parent is None: return component component = component.parent else: # pragma: no cover msg = _("parent circularity from {}") raise XMLSchemaValueError(msg.format(self))
(self) -> xmlschema.validators.xsdbase.XsdComponent
713,760
xmlschema.validators.xsdbase
get_matching_item
If a key is matching component name, returns its value, otherwise returns `None`.
def get_matching_item(self, mapping: MutableMapping[str, Any], ns_prefix: str = 'xmlns', match_local_name: bool = False) -> Optional[Any]: """ If a key is matching component name, returns its value, otherwise returns `None`. """ if self.name is None: return None elif not self.target_namespace: return mapping.get(self.name) elif self.qualified_name in mapping: return mapping[cast(str, self.qualified_name)] elif self.prefixed_name in mapping: return mapping[cast(str, self.prefixed_name)] # Try a match with other prefixes target_namespace = self.target_namespace suffix = f':{self.local_name}' for k in filter(lambda x: x.endswith(suffix), mapping): prefix = k.split(':')[0] if self.namespaces.get(prefix) == target_namespace: return mapping[k] # Match namespace declaration within value ns_declaration = f'{ns_prefix}:{prefix}' try: if mapping[k][ns_declaration] == target_namespace: return mapping[k] except (KeyError, TypeError): pass else: if match_local_name: return mapping.get(self.local_name) # type: ignore[arg-type] return None
(self, mapping: MutableMapping[str, Any], ns_prefix: str = 'xmlns', match_local_name: bool = False) -> Optional[Any]
713,761
xmlschema.validators.xsdbase
get_parent_type
Returns the nearest XSD type that contains the component instance, or `None` if the component doesn't have an XSD type parent.
def get_parent_type(self) -> Optional['XsdType']: """ Returns the nearest XSD type that contains the component instance, or `None` if the component doesn't have an XSD type parent. """ component = self.parent while component is not self and component is not None: if isinstance(component, XsdType): return component component = component.parent return None
(self) -> Optional[xmlschema.validators.xsdbase.XsdType]
713,762
xmlschema.validators.xsdbase
is_global
Returns `True` if the instance is a global component, `False` if it's local.
def is_global(self) -> bool: """Returns `True` if the instance is a global component, `False` if it's local.""" return self.parent is None
(self) -> bool
713,763
xmlschema.validators.xsdbase
is_matching
Returns `True` if the component name is matching the name provided as argument, `False` otherwise. For XSD elements the matching is extended to substitutes. :param name: a local or fully-qualified name. :param default_namespace: used by the XPath processor for completing the name argument in case it's a local name. :param kwargs: additional options that can be used by certain components.
def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> bool: """ Returns `True` if the component name is matching the name provided as argument, `False` otherwise. For XSD elements the matching is extended to substitutes. :param name: a local or fully-qualified name. :param default_namespace: used by the XPath processor for completing \ the name argument in case it's a local name. :param kwargs: additional options that can be used by certain components. """ return bool(self.name == name or default_namespace and name and name[0] != '{' and self.name == f'{{{default_namespace}}}{name}')
(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> bool
713,764
xmlschema.validators.attributes
is_optional
null
def is_optional(self) -> bool: return self.use == 'optional'
(self) -> bool
713,765
xmlschema.validators.xsdbase
is_override
Returns `True` if the instance is an override of a global component.
def is_override(self) -> bool: """Returns `True` if the instance is an override of a global component.""" if self.parent is not None: return False return any(self.elem in x for x in self.schema.root if x.tag == XSD_OVERRIDE)
(self) -> bool
713,766
xmlschema.validators.attributes
is_prohibited
null
def is_prohibited(self) -> bool: return self.use == 'prohibited'
(self) -> bool
713,767
xmlschema.validators.attributes
is_required
null
def is_required(self) -> bool: return self.use == 'required'
(self) -> bool
713,768
xmlschema.validators.xsdbase
is_valid
Like :meth:`validate` except that does not raise an exception but returns ``True`` if the XML data instance is valid, ``False`` if it is invalid.
def is_valid(self, obj: ST, use_defaults: bool = True, namespaces: Optional[NamespacesType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None) -> bool: """ Like :meth:`validate` except that does not raise an exception but returns ``True`` if the XML data instance is valid, ``False`` if it is invalid. """ error = next(self.iter_errors(obj, use_defaults, namespaces, max_depth, extra_validator), None) return error is None
(self, obj: ~ST, use_defaults: bool = True, namespaces: Optional[~T] = None, max_depth: Optional[int] = None, extra_validator: Optional[~T] = None) -> bool
713,769
xmlschema.validators.xsdbase
iter_ancestors
Creates an iterator for XSD ancestor components, schema excluded. Stops when the component is global or if the ancestor is not an instance of the specified class/classes. :param xsd_classes: provide a class or a tuple of classes to iterate over only a specific classes of components.
def iter_ancestors(self, xsd_classes: ComponentClassType = None)\ -> Iterator['XsdComponent']: """ Creates an iterator for XSD ancestor components, schema excluded. Stops when the component is global or if the ancestor is not an instance of the specified class/classes. :param xsd_classes: provide a class or a tuple of classes to iterate \ over only a specific classes of components. """ ancestor = self while True: if ancestor.parent is None: break ancestor = ancestor.parent if xsd_classes is not None and not isinstance(ancestor, xsd_classes): break yield ancestor
(self, xsd_classes: Optional[~T] = None) -> Iterator[xmlschema.validators.xsdbase.XsdComponent]
713,770
xmlschema.validators.attributes
iter_components
null
def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator[XsdComponent]: if xsd_classes is None or isinstance(self, xsd_classes): yield self if self.ref is None and self.type.parent is not None: yield from self.type.iter_components(xsd_classes)
(self, xsd_classes: Optional[~T] = None) -> Iterator[xmlschema.validators.xsdbase.XsdComponent]
713,771
xmlschema.validators.attributes
iter_decode
null
def iter_decode(self, obj: str, validation: str = 'lax', **kwargs: Any) \ -> IterDecodeType[DecodedValueType]: if obj is None and self.default is not None: obj = self.default if self.type.is_notation(): if self.type.name == XSD_NOTATION_TYPE: msg = _("cannot validate against xs:NOTATION directly, " "only against a subtype with an enumeration facet") yield self.validation_error(validation, msg, obj, **kwargs) elif not self.type.enumeration: msg = _("missing enumeration facet in xs:NOTATION subtype") yield self.validation_error(validation, msg, obj, **kwargs) if self.fixed is not None: if obj is None: obj = self.fixed elif obj != self.fixed and \ self.type.text_decode(obj) != self.type.text_decode(self.fixed): msg = _("attribute {0!r} has a fixed value {1!r}").format(self.name, self.fixed) yield self.validation_error(validation, msg, obj, **kwargs) for value in self.type.iter_decode(obj, validation, **kwargs): if isinstance(value, XMLSchemaValidationError): value.reason = _('attribute {0}={1!r}: {2}').format( self.prefixed_name, obj, value.reason ) yield value continue elif 'value_hook' in kwargs: yield kwargs['value_hook'](value, self.type) elif isinstance(value, (int, float, list)) or value is None: yield value elif isinstance(value, str): if value.startswith('{') and self.type.is_qname(): yield obj else: yield value elif isinstance(value, Decimal): try: yield kwargs['decimal_type'](value) except (KeyError, TypeError): yield value elif isinstance(value, (AbstractDateTime, Duration)): yield value if kwargs.get('datetime_types') else obj.strip() elif isinstance(value, AbstractBinary) and not kwargs.get('binary_types'): yield str(value) else: yield value break # pragma: no cover
(self, obj: str, validation: str = 'lax', **kwargs: Any) -> Optional[~T]
713,772
xmlschema.validators.attributes
iter_encode
null
def iter_encode(self, obj: Any, validation: str = 'lax', **kwargs: Any) \ -> IterEncodeType[Union[EncodedValueType]]: yield from self.type.iter_encode(obj, validation, **kwargs)
(self, obj: Any, validation: str = 'lax', **kwargs: Any) -> Optional[~T]
713,773
xmlschema.validators.xsdbase
iter_errors
Creates an iterator for the errors generated by the validation of an XML data against the XSD schema/component instance. Accepts the same arguments of :meth:`validate`.
def iter_errors(self, obj: ST, use_defaults: bool = True, namespaces: Optional[NamespacesType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None) \ -> Iterator[XMLSchemaValidationError]: """ Creates an iterator for the errors generated by the validation of an XML data against the XSD schema/component instance. Accepts the same arguments of :meth:`validate`. """ kwargs: Dict[str, Any] = { 'use_defaults': use_defaults, 'namespaces': namespaces, } if max_depth is not None: kwargs['max_depth'] = max_depth if extra_validator is not None: kwargs['extra_validator'] = extra_validator for result in self.iter_decode(obj, **kwargs): if isinstance(result, XMLSchemaValidationError): yield result else: del result
(self, obj: ~ST, use_defaults: bool = True, namespaces: Optional[~T] = None, max_depth: Optional[int] = None, extra_validator: Optional[~T] = None) -> Iterator[xmlschema.validators.exceptions.XMLSchemaValidationError]
713,774
xmlschema.validators.xsdbase
match
Returns the component if its name is matching the name provided as argument, `None` otherwise.
def match(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> Optional['XsdComponent']: """ Returns the component if its name is matching the name provided as argument, `None` otherwise. """ return self if self.is_matching(name, default_namespace, **kwargs) else None
(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> Optional[xmlschema.validators.xsdbase.XsdComponent]
713,776
xmlschema.validators.xsdbase
tostring
Serializes the XML elements that declare or define the component to a string.
def tostring(self, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: int = 4) -> Union[str, bytes]: """Serializes the XML elements that declare or define the component to a string.""" return etree_tostring(self.schema_elem, self.namespaces, indent, max_lines, spaces_for_tab)
(self, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: int = 4) -> Union[str, bytes]
713,777
xmlschema.validators.xsdbase
validate
Validates XML data against the XSD schema/component instance. :param obj: the XML data. 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. :param max_depth: maximum level of validation, for default there is no limit. :param extra_validator: an optional function for performing non-standard validations on XML data. The provided function is called for each traversed element, with the XML element as 1st argument and the corresponding XSD element as 2nd argument. It can be also a generator function and has to raise/yield :exc:`xmlschema.XMLSchemaValidationError` exceptions. :raises: :exc:`xmlschema.XMLSchemaValidationError` if the XML data instance is invalid.
def validate(self, obj: ST, use_defaults: bool = True, namespaces: Optional[NamespacesType] = None, max_depth: Optional[int] = None, extra_validator: Optional[ExtraValidatorType] = None) -> None: """ Validates XML data against the XSD schema/component instance. :param obj: the XML data. 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. :param max_depth: maximum level of validation, for default there is no limit. :param extra_validator: an optional function for performing non-standard \ validations on XML data. The provided function is called for each traversed \ element, with the XML element as 1st argument and the corresponding XSD \ element as 2nd argument. It can be also a generator function and has to \ raise/yield :exc:`xmlschema.XMLSchemaValidationError` exceptions. :raises: :exc:`xmlschema.XMLSchemaValidationError` if the XML data instance is invalid. """ for error in self.iter_errors(obj, use_defaults, namespaces, max_depth, extra_validator): raise error
(self, obj: ~ST, use_defaults: bool = True, namespaces: Optional[~T] = None, max_depth: Optional[int] = None, extra_validator: Optional[~T] = None) -> NoneType
713,779
xmlschema.validators.xsdbase
XsdComponent
Class for XSD components. See: https://www.w3.org/TR/xmlschema-ref/ :param elem: ElementTree's node containing the definition. :param schema: the XMLSchema object that owns the definition. :param parent: the XSD parent, `None` means that is a global component that has the schema as parent. :param name: name of the component, maybe overwritten by the parse of the `elem` argument. :cvar qualified: for name matching, unqualified matching may be admitted only for elements and attributes. :vartype qualified: bool
class XsdComponent(XsdValidator): """ Class for XSD components. See: https://www.w3.org/TR/xmlschema-ref/ :param elem: ElementTree's node containing the definition. :param schema: the XMLSchema object that owns the definition. :param parent: the XSD parent, `None` means that is a global component that \ has the schema as parent. :param name: name of the component, maybe overwritten by the parse of the `elem` argument. :cvar qualified: for name matching, unqualified matching may be admitted only \ for elements and attributes. :vartype qualified: bool """ _REGEX_SPACE = re.compile(r'\s') _REGEX_SPACES = re.compile(r'\s+') _ADMITTED_TAGS: Union[Set[str], Tuple[str, ...], Tuple[()]] = () elem: ElementType parent = None name = None ref: Optional['XsdComponent'] = None qualified = True redefine = None _annotation = None _annotations: List['XsdAnnotation'] _target_namespace: Optional[str] def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional['XsdComponent'] = None, name: Optional[str] = None) -> None: super().__init__(schema.validation) if name: self.name = name if parent is not None: self.parent = parent self.schema = schema self.maps: XsdGlobals = schema.maps self.elem = elem def __setattr__(self, name: str, value: Any) -> None: if name == 'elem': if value.tag not in self._ADMITTED_TAGS: msg = "wrong XSD element {!r} for {!r}, must be one of {!r}" raise XMLSchemaValueError( msg.format(value.tag, self.__class__, self._ADMITTED_TAGS) ) super().__setattr__(name, value) if self.errors: self.errors.clear() self._parse() else: super().__setattr__(name, value) @property def xsd_version(self) -> str: return self.schema.XSD_VERSION def is_global(self) -> bool: """Returns `True` if the instance is a global component, `False` if it's local.""" return self.parent is None def is_override(self) -> bool: """Returns `True` if the instance is an override of a global component.""" if self.parent is not None: return False return any(self.elem in x for x in self.schema.root if x.tag == XSD_OVERRIDE) @property def schema_elem(self) -> ElementType: """The reference element of the schema for the component instance.""" return self.elem @property def source(self) -> XMLResource: """Property that references to schema source.""" return self.schema.source @property def target_namespace(self) -> str: """Property that references to schema's targetNamespace.""" return self.schema.target_namespace if self.ref is None else self.ref.target_namespace @property def default_namespace(self) -> Optional[str]: """Property that references to schema's default namespaces.""" return self.schema.namespaces.get('') @property def namespaces(self) -> NamespacesType: """Property that references to schema's namespace mapping.""" return self.schema.namespaces @property def any_type(self) -> 'XsdComplexType': """Property that references to the xs:anyType instance of the global maps.""" return cast('XsdComplexType', self.maps.types[XSD_ANY_TYPE]) @property def any_simple_type(self) -> 'XsdSimpleType': """Property that references to the xs:anySimpleType instance of the global maps.""" return cast('XsdSimpleType', self.maps.types[XSD_ANY_SIMPLE_TYPE]) @property def any_atomic_type(self) -> 'XsdSimpleType': """Property that references to the xs:anyAtomicType instance of the global maps.""" return cast('XsdSimpleType', self.maps.types[XSD_ANY_ATOMIC_TYPE]) @property def annotation(self) -> Optional['XsdAnnotation']: """ The primary annotation of the XSD component, if any. This is the annotation defined in the first child of the element where the component is defined. """ if '_annotation' not in self.__dict__: child = get_xsd_annotation_child(self.elem) if child is not None: self._annotation = XsdAnnotation(child, self.schema, self) else: self._annotation = None return self._annotation @property def annotations(self) -> List['XsdAnnotation']: """A list containing all the annotations of the XSD component.""" if '_annotations' not in self.__dict__: self._annotations = [] components = self.schema.components parent_map = self.schema.source.parent_map for elem in self.elem.iter(): if elem is self.elem: annotation = self.annotation if annotation is not None: self._annotations.append(annotation) elif elem in components: break elif elem.tag == XSD_ANNOTATION: parent_elem = parent_map[elem] self._annotations.append(XsdAnnotation(elem, self.schema, self, parent_elem)) return self._annotations def __repr__(self) -> str: if self.ref is not None: return '%s(ref=%r)' % (self.__class__.__name__, self.prefixed_name) else: return '%s(name=%r)' % (self.__class__.__name__, self.prefixed_name) def _parse(self) -> None: return def _parse_reference(self) -> Optional[bool]: """ Helper method for referable components. Returns `True` if a valid reference QName is found without any error, otherwise returns `None`. Sets an id-related name for the component ('nameless_<id of the instance>') if both the attributes 'ref' and 'name' are missing. """ ref = self.elem.get('ref') if ref is None: if 'name' in self.elem.attrib: return None elif self.parent is None: msg = _("missing attribute 'name' in a global %r") self.parse_error(msg % type(self)) else: msg = _("missing both attributes 'name' and 'ref' in local %r") self.parse_error(msg % type(self)) elif 'name' in self.elem.attrib: msg = _("attributes 'name' and 'ref' are mutually exclusive") self.parse_error(msg) elif self.parent is None: msg = _("attribute 'ref' not allowed in a global %r") self.parse_error(msg % type(self)) else: try: self.name = self.schema.resolve_qname(ref) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) else: if self._parse_child_component(self.elem, strict=False) is not None: msg = _("a reference component cannot have child definitions/declarations") self.parse_error(msg) return True return None def _parse_child_component(self, elem: ElementType, strict: bool = True) \ -> Optional[ElementType]: child = None for e in elem: if e.tag == XSD_ANNOTATION or callable(e.tag): continue elif not strict: return e elif child is not None: msg = _("too many XSD components, unexpected {0!r} found at position {1}") self.parse_error(msg.format(child, elem[:].index(e)), elem) break else: child = e return child def _parse_target_namespace(self) -> None: """ XSD 1.1 targetNamespace attribute in elements and attributes declarations. """ if 'targetNamespace' not in self.elem.attrib: return self._target_namespace = self.elem.attrib['targetNamespace'].strip() if self._target_namespace == XMLNS_NAMESPACE: # https://www.w3.org/TR/xmlschema11-1/#sec-nss-special msg = _(f"The namespace {XMLNS_NAMESPACE} cannot be used as 'targetNamespace'") raise XMLSchemaValueError(msg) if 'name' not in self.elem.attrib: msg = _("attribute 'name' must be present when " "'targetNamespace' attribute is provided") self.parse_error(msg) if 'form' in self.elem.attrib: msg = _("attribute 'form' must be absent when " "'targetNamespace' attribute is provided") self.parse_error(msg) if self._target_namespace != self.schema.target_namespace: if self.parent is None: msg = _("a global %s must have the same namespace as its parent schema") self.parse_error(msg % self.__class__.__name__) xsd_type = self.get_parent_type() if xsd_type is None or xsd_type.parent is not None: pass elif xsd_type.derivation != 'restriction' or \ getattr(xsd_type.base_type, 'name', None) == XSD_ANY_TYPE: msg = _("a declaration contained in a global complexType " "must have the same namespace as its parent schema") self.parse_error(msg) if self.name is None: pass # pragma: no cover elif not self._target_namespace: self.name = local_name(self.name) else: self.name = f'{{{self._target_namespace}}}{local_name(self.name)}' def _get_converter(self, obj: Any, kwargs: Dict[str, Any]) -> XMLSchemaConverter: if 'source' not in kwargs: if isinstance(obj, XMLResource): kwargs['source'] = obj elif is_etree_element(obj) or is_etree_document(obj): kwargs['source'] = XMLResource(obj) else: kwargs['source'] = obj converter = kwargs['converter'] = self.schema.get_converter(**kwargs) kwargs['namespaces'] = converter.namespaces return converter @property def local_name(self) -> Optional[str]: """The local part of the name of the component, or `None` if the name is `None`.""" return None if self.name is None else local_name(self.name) @property def qualified_name(self) -> Optional[str]: """The name of the component in extended format, or `None` if the name is `None`.""" return None if self.name is None else get_qname(self.target_namespace, self.name) @property def prefixed_name(self) -> Optional[str]: """The name of the component in prefixed format, or `None` if the name is `None`.""" return None if self.name is None else get_prefixed_qname(self.name, self.namespaces) @property def display_name(self) -> Optional[str]: """ The name of the component to display when you have to refer to it with a simple unambiguous format. """ prefixed_name = self.prefixed_name if prefixed_name is None: return None return self.name if ':' not in prefixed_name else prefixed_name @property def id(self) -> Optional[str]: """The ``'id'`` attribute of the component tag, ``None`` if missing.""" return self.elem.get('id') @property def validation_attempted(self) -> str: return 'full' if self.built else 'partial' def build(self) -> None: """ Builds components that are not fully parsed at initialization, like model groups or internal local elements in model groups, otherwise does nothing. """ @property def built(self) -> bool: raise NotImplementedError() def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> bool: """ Returns `True` if the component name is matching the name provided as argument, `False` otherwise. For XSD elements the matching is extended to substitutes. :param name: a local or fully-qualified name. :param default_namespace: used by the XPath processor for completing \ the name argument in case it's a local name. :param kwargs: additional options that can be used by certain components. """ return bool(self.name == name or default_namespace and name and name[0] != '{' and self.name == f'{{{default_namespace}}}{name}') def match(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> Optional['XsdComponent']: """ Returns the component if its name is matching the name provided as argument, `None` otherwise. """ return self if self.is_matching(name, default_namespace, **kwargs) else None def get_matching_item(self, mapping: MutableMapping[str, Any], ns_prefix: str = 'xmlns', match_local_name: bool = False) -> Optional[Any]: """ If a key is matching component name, returns its value, otherwise returns `None`. """ if self.name is None: return None elif not self.target_namespace: return mapping.get(self.name) elif self.qualified_name in mapping: return mapping[cast(str, self.qualified_name)] elif self.prefixed_name in mapping: return mapping[cast(str, self.prefixed_name)] # Try a match with other prefixes target_namespace = self.target_namespace suffix = f':{self.local_name}' for k in filter(lambda x: x.endswith(suffix), mapping): prefix = k.split(':')[0] if self.namespaces.get(prefix) == target_namespace: return mapping[k] # Match namespace declaration within value ns_declaration = f'{ns_prefix}:{prefix}' try: if mapping[k][ns_declaration] == target_namespace: return mapping[k] except (KeyError, TypeError): pass else: if match_local_name: return mapping.get(self.local_name) # type: ignore[arg-type] return None def get_global(self) -> 'XsdComponent': """Returns the global XSD component that contains the component instance.""" if self.parent is None: return self component = self.parent while component is not self: if component.parent is None: return component component = component.parent else: # pragma: no cover msg = _("parent circularity from {}") raise XMLSchemaValueError(msg.format(self)) def get_parent_type(self) -> Optional['XsdType']: """ Returns the nearest XSD type that contains the component instance, or `None` if the component doesn't have an XSD type parent. """ component = self.parent while component is not self and component is not None: if isinstance(component, XsdType): return component component = component.parent return None def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator['XsdComponent']: """ Creates an iterator for XSD subcomponents. :param xsd_classes: provide a class or a tuple of classes to iterate \ over only a specific classes of components. """ if xsd_classes is None or isinstance(self, xsd_classes): yield self def iter_ancestors(self, xsd_classes: ComponentClassType = None)\ -> Iterator['XsdComponent']: """ Creates an iterator for XSD ancestor components, schema excluded. Stops when the component is global or if the ancestor is not an instance of the specified class/classes. :param xsd_classes: provide a class or a tuple of classes to iterate \ over only a specific classes of components. """ ancestor = self while True: if ancestor.parent is None: break ancestor = ancestor.parent if xsd_classes is not None and not isinstance(ancestor, xsd_classes): break yield ancestor def tostring(self, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: int = 4) -> Union[str, bytes]: """Serializes the XML elements that declare or define the component to a string.""" return etree_tostring(self.schema_elem, self.namespaces, indent, max_lines, spaces_for_tab)
(elem: Optional[~T], schema: Optional[~T], parent: Optional[ForwardRef('XsdComponent')] = None, name: Optional[str] = None) -> None
713,785
xmlschema.validators.xsdbase
_parse
null
def _parse(self) -> None: return
(self) -> NoneType
713,799
xmlschema.validators.xsdbase
iter_components
Creates an iterator for XSD subcomponents. :param xsd_classes: provide a class or a tuple of classes to iterate over only a specific classes of components.
def iter_components(self, xsd_classes: ComponentClassType = None) \ -> Iterator['XsdComponent']: """ Creates an iterator for XSD subcomponents. :param xsd_classes: provide a class or a tuple of classes to iterate \ over only a specific classes of components. """ if xsd_classes is None or isinstance(self, xsd_classes): yield self
(self, xsd_classes: Optional[~T] = None) -> Iterator[xmlschema.validators.xsdbase.XsdComponent]
713,804
xmlschema.validators.elements
XsdElement
Class for XSD 1.0 *element* declarations. :ivar type: the XSD simpleType or complexType of the element. :ivar attributes: the group of the attributes associated with the element. .. <element abstract = boolean : false block = (#all | List of (extension | restriction | substitution)) default = string final = (#all | List of (extension | restriction)) fixed = string form = (qualified | unqualified) id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName nillable = boolean : false ref = QName substitutionGroup = QName type = QName {any attributes with non-schema namespace . . .}> Content: (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*)) </element>
class XsdElement(XsdComponent, ParticleMixin, ElementPathMixin[SchemaElementType], ValidationMixin[ElementType, Any]): """ Class for XSD 1.0 *element* declarations. :ivar type: the XSD simpleType or complexType of the element. :ivar attributes: the group of the attributes associated with the element. .. <element abstract = boolean : false block = (#all | List of (extension | restriction | substitution)) default = string final = (#all | List of (extension | restriction)) fixed = string form = (qualified | unqualified) id = ID maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName nillable = boolean : false ref = QName substitutionGroup = QName type = QName {any attributes with non-schema namespace . . .}> Content: (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*)) </element> """ name: str local_name: str qualified_name: str prefixed_name: str parent: Optional['XsdGroup'] ref: Optional['XsdElement'] attributes: 'XsdAttributeGroup' type: BaseXsdType abstract = False nillable = False qualified = False form: Optional[str] = None default: Optional[str] = None fixed: Optional[str] = None substitution_group: Optional[str] = None identities: List[XsdIdentity] selected_by: Set[XsdIdentity] alternatives = () # type: Union[Tuple[()], List[XsdAlternative]] inheritable = () # type: Union[Tuple[()], Dict[str, XsdAttribute]] _ADMITTED_TAGS = {XSD_ELEMENT} _block: Optional[str] = None _final: Optional[str] = None _head_type = None _build = True binding: Optional[DataBindingType] = None def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[XsdComponent] = None, build: bool = True) -> None: if not build: self._build = False self.selected_by = set() super().__init__(elem, schema, parent) def __repr__(self) -> str: return '%s(%s=%r, occurs=%r)' % ( self.__class__.__name__, 'name' if self.ref is None else 'ref', self.prefixed_name, list(self.occurs) ) def __setattr__(self, name: str, value: Any) -> None: if name == "type": if isinstance(value, XsdSimpleType): self.attributes = self.schema.create_empty_attribute_group(self) else: self.attributes = value.attributes super().__setattr__(name, value) def __iter__(self) -> Iterator[SchemaElementType]: if self.type.has_complex_content(): yield from self.type.content.iter_elements() # type: ignore[union-attr] def _parse(self) -> None: if not self._build: return self._parse_particle(self.elem) self._parse_attributes() if self.ref is None: self._parse_type() self._parse_constraints() if self.parent is None and 'substitutionGroup' in self.elem.attrib: self._parse_substitution_group(self.elem.attrib['substitutionGroup']) def _parse_attributes(self) -> None: attrib = self.elem.attrib if self._parse_reference(): try: xsd_element: XsdElement = self.maps.lookup_element(self.name) except KeyError: self.type = self.any_type self.parse_error(_('unknown element %r') % self.name) else: self.ref = xsd_element self.type = xsd_element.type self.abstract = xsd_element.abstract self.nillable = xsd_element.nillable self.qualified = xsd_element.qualified self.form = xsd_element.form self.default = xsd_element.default self.fixed = xsd_element.fixed self.substitution_group = xsd_element.substitution_group self.identities = xsd_element.identities self.alternatives = xsd_element.alternatives self.selected_by = xsd_element.selected_by for attr_name in ('type', 'nillable', 'default', 'fixed', 'form', 'block', 'abstract', 'final', 'substitutionGroup'): if attr_name in attrib: msg = _("attribute {!r} is not allowed when element reference is used") self.parse_error(msg.format(attr_name)) return if 'form' in attrib: self.form = attrib['form'] if self.form == 'qualified': self.qualified = True elif self.schema.element_form_default == 'qualified': self.qualified = True try: if self.parent is None or self.qualified: self.name = get_qname(self.target_namespace, attrib['name']) else: self.name = attrib['name'] except KeyError: pass if 'abstract' in attrib: if self.parent is not None: msg = _("local scope elements cannot have abstract attribute") self.parse_error(msg) if attrib['abstract'].strip() in ('true', '1'): self.abstract = True if 'block' in attrib: try: self._block = get_xsd_derivation_attribute( self.elem, 'block', XSD_ELEMENT_DERIVATIONS ) except ValueError as err: self.parse_error(err) if 'nillable' in attrib and attrib['nillable'].strip() in ('true', '1'): self.nillable = True if self.parent is None: if 'final' in attrib: try: self._final = get_xsd_derivation_attribute( self.elem, 'final', XSD_TYPE_DERIVATIONS ) except ValueError as err: self.parse_error(err) for attr_name in ('ref', 'form', 'minOccurs', 'maxOccurs'): if attr_name in attrib: msg = _("attribute {!r} is not allowed in a global element declaration") self.parse_error(msg.format(attr_name)) else: for attr_name in ('final', 'substitutionGroup'): if attr_name in attrib: msg = _("attribute {!r} not allowed in a local element declaration") self.parse_error(msg.format(attr_name)) def _parse_type(self) -> None: type_name = self.elem.get('type') if type_name is not None: try: extended_name = self.schema.resolve_qname(type_name) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) self.type = self.any_type else: if extended_name == XSD_ANY_TYPE: self.type = self.any_type else: try: self.type = self.maps.lookup_type(extended_name) except KeyError: self.parse_error(_('unknown type {!r}').format(type_name)) self.type = self.any_type finally: child = self._parse_child_component(self.elem, strict=False) if child is not None and child.tag in (XSD_COMPLEX_TYPE, XSD_SIMPLE_TYPE): msg = _("the attribute 'type' and a xs:{} local " "declaration are mutually exclusive") self.parse_error(msg.format(child.tag.split('}')[-1])) else: child = self._parse_child_component(self.elem, strict=False) if child is None: self.type = self.any_type elif child.tag == XSD_COMPLEX_TYPE: self.type = self.schema.xsd_complex_type_class(child, self.schema, self) elif child.tag == XSD_SIMPLE_TYPE: self.type = self.schema.simple_type_factory(child, self.schema, self) else: self.type = self.any_type def _parse_constraints(self) -> None: # Value constraints if 'default' in self.elem.attrib: self.default = self.elem.attrib['default'] if 'fixed' in self.elem.attrib: msg = _("'default' and 'fixed' attributes are mutually exclusive") self.parse_error(msg) if not self.type.is_valid(self.default): msg = _("'default' value {!r} is not compatible with element's type") self.parse_error(msg.format(self.default)) self.default = None elif self.xsd_version == '1.0' and self.type.is_key(): msg = _("xs:ID or a type derived from xs:ID cannot have a default value") self.parse_error(msg) elif 'fixed' in self.elem.attrib: self.fixed = self.elem.attrib['fixed'] if not self.type.is_valid(self.fixed): msg = _("'fixed' value {!r} is not compatible with element's type") self.parse_error(msg.format(self.fixed)) self.fixed = None elif self.xsd_version == '1.0' and self.type.is_key(): msg = _("xs:ID or a type derived from xs:ID cannot have a fixed value") self.parse_error(msg) # Identity constraints self.identities = [] constraint: Union[XsdKey, XsdUnique, XsdKeyref] for child in self.elem: if child.tag == XSD_UNIQUE: constraint = self.schema.xsd_unique_class(child, self.schema, self) elif child.tag == XSD_KEY: constraint = self.schema.xsd_key_class(child, self.schema, self) elif child.tag == XSD_KEYREF: constraint = self.schema.xsd_keyref_class(child, self.schema, self) else: # Invalid tags already caught by validation against the meta-schema continue if constraint.ref: if any(constraint.name == x.name for x in self.identities): msg = _("duplicated identity constraint %r:") self.parse_error(msg % constraint.name, child) self.identities.append(constraint) continue try: if child != self.maps.identities[constraint.name].elem: msg = _("duplicated identity constraint %r:") self.parse_error(msg % constraint.name, child) except KeyError: self.maps.identities[constraint.name] = constraint finally: self.identities.append(constraint) def _parse_substitution_group(self, substitution_group: str) -> None: try: substitution_group_qname = self.schema.resolve_qname(substitution_group) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) return else: if substitution_group_qname[0] != '{': substitution_group_qname = get_qname( self.target_namespace, substitution_group_qname ) try: head_element = self.maps.lookup_element(substitution_group_qname) except KeyError: msg = _("unknown substitutionGroup %r") self.parse_error(msg % substitution_group) return else: if isinstance(head_element, tuple): msg = _("circularity found for substitutionGroup %r") self.parse_error(msg % substitution_group) return elif 'substitution' in head_element.block: return final = head_element.final if self.type == head_element.type: pass elif self.type.name == XSD_ANY_TYPE: if head_element.type.name != XSD_ANY_TYPE: # Use head element's type for validate content # ref: https://www.w3.org/TR/xmlschema-1/#cElement_Declarations self._head_type = head_element.type elif not self.type.is_derived(head_element.type): msg = _("{0!r} type is not of the same or a derivation " "of the head element {1!r} type") self.parse_error(msg.format(self, head_element)) elif final == '#all' or 'extension' in final and 'restriction' in final: msg = _("head element %r can't be substituted by an " "element that has a derivation of its type") self.parse_error(msg % head_element) elif 'extension' in final and self.type.is_derived(head_element.type, 'extension'): msg = _("head element %r can't be substituted by an " "element that has an extension of its type") self.parse_error(msg % head_element) elif 'restriction' in final and self.type.is_derived(head_element.type, 'restriction'): msg = _("head element %r can't be substituted by an " "element that has a restriction of its type") self.parse_error(msg % head_element) try: self.maps.substitution_groups[substitution_group_qname].add(self) except KeyError: self.maps.substitution_groups[substitution_group_qname] = {self} finally: self.substitution_group = substitution_group_qname @property def xpath_proxy(self) -> XMLSchemaProxy: return XMLSchemaProxy(self.schema, self) @property def xpath_node(self) -> SchemaElementNode: schema_node = self.schema.xpath_node node = schema_node.get_element_node(self) if isinstance(node, SchemaElementNode): return node return build_schema_node_tree( root=self, elements=schema_node.elements, global_elements=schema_node.children, ) def build(self) -> None: if self._build: return None self._build = True self._parse() @property def built(self) -> bool: return hasattr(self, 'type') and \ (self.type.parent is None or self.type.built) and \ all(c.built for c in self.identities) @property def validation_attempted(self) -> str: if self.built: return 'full' elif self.type.validation_attempted == 'partial': return 'partial' elif any(c.validation_attempted == 'partial' for c in self.identities): return 'partial' else: return 'none' @property def scope(self) -> str: """The scope of the element declaration that can be 'global' or 'local'.""" return 'global' if self.parent is None else 'local' @property def value_constraint(self) -> Optional[str]: """The fixed or the default value if either is defined, `None` otherwise.""" return self.fixed if self.fixed is not None else self.default @property def final(self) -> str: if self.ref is not None: return self.ref.final elif self._final is not None: return self._final return self.schema.final_default @property def block(self) -> str: if self.ref is not None: return self.ref.block elif self._block is not None: return self._block return self.schema.block_default def get_binding(self, *bases: Type[Any], replace_existing: bool = False, **attrs: Any) \ -> DataBindingType: """ Gets data object binding for XSD element, creating a new one if it doesn't exist. :param bases: base classes to use for creating the binding class. :param replace_existing: provide `True` to replace an existing binding class. :param attrs: attribute and method definitions for the binding class body. """ if self.binding is None or replace_existing: if not bases: bases = (dataobjects.DataElement,) attrs['xsd_element'] = self class_name = '{}Binding'.format(self.local_name.title().replace('_', '')) self.binding = cast(DataBindingType, dataobjects.DataBindingMeta(class_name, bases, attrs)) return self.binding def get_type(self, elem: Union[ElementType, ElementData], inherited: Optional[Dict[str, Any]] = None) -> BaseXsdType: return self._head_type or self.type def get_attributes(self, xsd_type: BaseXsdType) -> 'XsdAttributeGroup': if not isinstance(xsd_type, XsdSimpleType): return xsd_type.attributes elif xsd_type is self.type: return self.attributes else: return self.schema.create_empty_attribute_group(self) def get_path(self, ancestor: Optional[XsdComponent] = None, reverse: bool = False) -> Optional[str]: """ Returns the XPath expression of the element. The path is relative to the schema instance in which the element is contained or is relative to a specific ancestor passed as argument. In the latter case returns `None` if the argument is not an ancestor. :param ancestor: optional XSD component of the same schema, that maybe \ an ancestor of the element. :param reverse: if set to `True` returns the reverse path, from the element to ancestor. """ path: List[str] = [] xsd_component: Optional[XsdComponent] = self while xsd_component is not None: if xsd_component is ancestor: return '/'.join(reversed(path)) or '.' elif isinstance(xsd_component, XsdElement): path.append('..' if reverse else xsd_component.name) xsd_component = xsd_component.parent else: if ancestor is None: return '/'.join(reversed(path)) or '.' return None def iter_components(self, xsd_classes: Optional[ComponentClassType] = None) \ -> Iterator[XsdComponent]: if xsd_classes is None: yield self yield from self.identities else: if isinstance(self, xsd_classes): yield self if issubclass(XsdIdentity, xsd_classes): yield from self.identities if self.ref is None and self.type.parent is not None: yield from self.type.iter_components(xsd_classes) def iter_substitutes(self) -> Iterator['XsdElement']: if self.parent is None or self.ref is not None: for xsd_element in self.maps.substitution_groups.get(self.name, ()): if not xsd_element.abstract: yield xsd_element for e in xsd_element.iter_substitutes(): if not e.abstract: yield e def data_value(self, elem: ElementType) -> Optional[AtomicValueType]: """Returns the decoded data value of the provided element as XPath fn:data().""" text = elem.text if text is None: text = self.fixed if self.fixed is not None else self.default if text is None: if self.type.is_valid(''): self.type.text_decode('') return None return self.type.text_decode(text) def check_dynamic_context(self, elem: ElementType, validation: str, options: Dict[str, Any]) -> Iterator[XMLSchemaValidationError]: try: source: XMLResource = options['source'] except KeyError: return for ns, url in etree_iter_location_hints(elem): base_url = source.base_url url = normalize_url(url, base_url) if any(url == schema.url for schema in self.maps.iter_schemas()): continue if ns in etree_iter_namespaces(source.root, elem): reason = _("schemaLocation declaration after namespace start") yield self.validation_error(validation, reason, elem, **options) try: if ns in self.maps.namespaces: schema = self.maps.namespaces[ns][0] schema.include_schema(url) self.schema.clear() self.schema.build() else: self.schema.import_schema(ns, url, base_url, build=True) except (XMLSchemaValidationError, ParseError) as err: yield self.validation_error(validation, err, elem, **options) except XMLSchemaParseError as err: yield self.validation_error(validation, err.message, elem, **options) except OSError: continue def iter_decode(self, obj: ElementType, validation: str = 'lax', **kwargs: Any) \ -> IterDecodeType[Any]: """ Creates an iterator for decoding an Element instance. :param obj: the Element that has to be decoded. :param validation: the validation mode, can be 'lax', 'strict' or 'skip'. :param kwargs: keyword arguments for the decoding process. :return: yields a decoded object, eventually preceded by a sequence of \ validation or decoding errors. """ error: Union[XMLSchemaValueError, XMLSchemaValidationError] result: Any if self.abstract: reason = _("cannot use an abstract element for validation") yield self.validation_error(validation, reason, obj, **kwargs) # Control validation on element and its descendants or stop validation if 'validation_hook' in kwargs: value = kwargs['validation_hook'](obj, self) if value: if isinstance(value, str) and value in XSD_VALIDATION_MODES: validation = value else: return kwargs['elem'] = obj try: level = kwargs['level'] except KeyError: level = kwargs['level'] = 0 try: identities = kwargs['identities'] except KeyError: identities = kwargs['identities'] = {} for identity in self.identities: if identity in identities: identities[identity].reset(obj) else: identities[identity] = identity.get_counter(obj) try: converter = kwargs['converter'] except KeyError: converter = self._get_converter(obj, kwargs) else: if not isinstance(converter, NamespaceMapper): converter = self._get_converter(obj, kwargs) if not level: # Need to set base context with the right object (the resource can be lazy) converter.set_context(obj, level) elif kwargs.get('use_location_hints'): # Use location hints for dynamic schema load yield from self.check_dynamic_context(obj, validation, options=kwargs) inherited = kwargs.get('inherited') value = content = attributes = None nilled = False # Get the instance effective type xsd_type = self.get_type(obj, inherited) if XSI_TYPE in obj.attrib and self.schema.meta_schema is not None: # Meta-schema elements ignore xsi:type (issue #350) type_name = obj.attrib[XSI_TYPE].strip() namespaces = converter.namespaces try: xsd_type = self.maps.get_instance_type(type_name, xsd_type, namespaces) except (KeyError, TypeError) as err: yield self.validation_error(validation, err, obj, **kwargs) else: if self.identities: xpath_element = XPathElement(self.name, xsd_type) for identity in self.identities: if isinstance(identity.elements, tuple) \ or identity.selector is None: continue # Skip unbuilt or incomplete identities elif identity.selector.token is None: raise XMLSchemaNotBuiltError( identity, "identity selector is not built" ) context = XPathContext(root=self.schema.xpath_node, item=xpath_element) for e in identity.selector.token.select_results(context): if isinstance(e, XsdElement): if e not in identity.elements: identity.elements[e] = None e.selected_by.add(identity) elif not isinstance(e, XsdAnyElement): reason = _("selector xpath expression can only select elements") yield self.validation_error(validation, reason, e, **kwargs) if xsd_type.is_blocked(self): reason = _("usage of %r is blocked") % xsd_type yield self.validation_error(validation, reason, obj, **kwargs) if xsd_type.abstract: reason = _("%r is abstract") % xsd_type yield self.validation_error(validation, reason, obj, **kwargs) if xsd_type.is_complex() and self.xsd_version == '1.1': kwargs['id_list'] = [] # Track XSD 1.1 multiple xs:ID attributes/children content_decoder = xsd_type if isinstance(xsd_type, XsdSimpleType) else xsd_type.content # Decode attributes attribute_group = self.get_attributes(xsd_type) for result in attribute_group.iter_decode(obj.attrib, validation, **kwargs): if isinstance(result, XMLSchemaValidationError): yield self.validation_error(validation, result, obj, **kwargs) else: attributes = result if self.inheritable and any(name in self.inheritable for name in obj.attrib): if inherited: inherited = inherited.copy() inherited.update((k, v) for k, v in obj.attrib.items() if k in self.inheritable) else: inherited = {k: v for k, v in obj.attrib.items() if k in self.inheritable} kwargs['inherited'] = inherited # Checks the xsi:nil attribute of the instance if XSI_NIL in obj.attrib: xsi_nil = obj.attrib[XSI_NIL].strip() if not self.nillable: reason = _("element is not nillable") yield self.validation_error(validation, reason, obj, **kwargs) elif xsi_nil not in ('0', '1', 'false', 'true'): reason = _("xsi:nil attribute must have a boolean value") yield self.validation_error(validation, reason, obj, **kwargs) elif xsi_nil in ('0', 'false'): pass elif self.fixed is not None: reason = _("xsi:nil='true' but the element has a fixed value") yield self.validation_error(validation, reason, obj, **kwargs) elif obj.text is not None or len(obj): reason = _("xsi:nil='true' but the element is not empty") yield self.validation_error(validation, reason, obj, **kwargs) else: nilled = True if xsd_type.is_empty() and obj.text and xsd_type.normalize(obj.text): reason = _("character data is not allowed because content is empty") yield self.validation_error(validation, reason, obj, **kwargs) if nilled: pass elif not isinstance(content_decoder, XsdSimpleType): if not isinstance(xsd_type, XsdSimpleType): for assertion in xsd_type.assertions: for error in assertion(obj, **kwargs): yield self.validation_error(validation, error, **kwargs) for result in content_decoder.iter_decode(obj, validation, **kwargs): if isinstance(result, XMLSchemaValidationError): yield self.validation_error(validation, result, obj, **kwargs) else: content = result if content and len(content) == 1 and content[0][0] == 1: value, content = content[0][1], None if self.fixed is not None and \ (len(obj) > 0 or value is not None and self.fixed != value): reason = _("must have the fixed value %r") % self.fixed yield self.validation_error(validation, reason, obj, **kwargs) else: if len(obj): reason = _("a simple content element can't have child elements") yield self.validation_error(validation, reason, obj, **kwargs) text = obj.text if self.fixed is not None: if not text: text = self.fixed elif text == self.fixed: pass elif not strictly_equal(xsd_type.text_decode(text), xsd_type.text_decode(self.fixed)): reason = _("must have the fixed value %r") % self.fixed yield self.validation_error(validation, reason, obj, **kwargs) elif not text and self.default is not None and kwargs.get('use_defaults', True): text = self.default if not isinstance(xsd_type, XsdSimpleType): for assertion in xsd_type.assertions: for error in assertion(obj, value=text, **kwargs): yield self.validation_error(validation, error, **kwargs) if text and content_decoder.is_list(): value = text.split() else: value = text elif xsd_type.is_notation(): if xsd_type.name == XSD_NOTATION_TYPE: msg = _("cannot validate against xs:NOTATION directly, " "only against a subtype with an enumeration facet") yield self.validation_error(validation, msg, text, **kwargs) elif not xsd_type.enumeration: msg = _("missing enumeration facet in xs:NOTATION subtype") yield self.validation_error(validation, msg, text, **kwargs) for result in content_decoder.iter_decode(text or '', validation, **kwargs): if isinstance(result, XMLSchemaValidationError): yield self.validation_error(validation, result, obj, **kwargs) elif result is None and 'filler' in kwargs: value = kwargs['filler'](self) elif text or kwargs.get('keep_empty'): value = result if 'value_hook' in kwargs: value = kwargs['value_hook'](value, xsd_type) elif isinstance(value, (int, float, list)) or value is None: pass elif isinstance(value, str): if value.startswith('{') and xsd_type.is_qname(): value = text elif isinstance(value, Decimal): try: value = kwargs['decimal_type'](value) except (KeyError, TypeError): pass elif isinstance(value, (AbstractDateTime, Duration)): if not kwargs.get('datetime_types'): value = str(value) if text is None else text.strip() elif isinstance(value, AbstractBinary): if not kwargs.get('binary_types'): value = str(value) xmlns = converter.set_context(obj, level) # Purge existing sub-contexts if isinstance(converter, XMLSchemaConverter): element_data = ElementData(obj.tag, value, content, attributes, xmlns) if 'element_hook' in kwargs: element_data = kwargs['element_hook'](element_data, self, xsd_type) try: yield converter.element_decode(element_data, self, xsd_type, level) except (ValueError, TypeError) as err: yield self.validation_error(validation, err, obj, **kwargs) elif not level: yield ElementData(obj.tag, value, None, attributes, None) if content is not None: del content if self.selected_by: yield from self.collect_key_fields(obj, xsd_type, validation, nilled, **kwargs) # Apply non XSD optional validations if 'extra_validator' in kwargs: try: result = kwargs['extra_validator'](obj, self) except XMLSchemaValidationError as err: yield self.validation_error(validation, err, obj, **kwargs) else: if isinstance(result, GeneratorType): for error in result: yield self.validation_error(validation, error, obj, **kwargs) # Disable collect for out of scope identities and check key references if 'max_depth' not in kwargs: for identity in self.identities: counter = identities[identity] counter.enabled = False if isinstance(identity, XsdKeyref): assert isinstance(counter, KeyrefCounter) for error in counter.iter_errors(identities): yield self.validation_error(validation, error, obj, **kwargs) elif level: for identity in self.identities: identities[identity].enabled = False def collect_key_fields(self, obj: ElementType, xsd_type: BaseXsdType, validation: str = 'lax', nilled: bool = False, **kwargs: Any) -> Iterator[XMLSchemaValidationError]: element_node: Union[ElementNode, LazyElementNode] xsd_fields: Optional[IdentityCounterType] try: identities = kwargs['identities'] resource = cast(XMLResource, kwargs['source']) except KeyError: # skip identities collect if identity map or XML source are missing return try: namespaces = kwargs['namespaces'] except KeyError: namespaces = None element_node = resource.get_xpath_node(obj) xsd_element = self if self.ref is None else self.ref if xsd_element.type is not xsd_type: xsd_element = _copy(xsd_element) xsd_element.type = xsd_type # Collect field values for identities that refer to this element. for identity in self.selected_by: try: counter = identities[identity] except KeyError: continue else: if not counter.enabled or not identity.elements: continue if counter.elements is None: # Apply selector on Element ancestor for obtain the selected elements root_node = resource.get_xpath_node(counter.elem) context = XPathContext(root_node) assert identity.selector is not None and identity.selector.token is not None counter.elements = set(identity.selector.token.select_results(context)) if obj not in counter.elements: continue try: if xsd_element.type is self.type and xsd_element in identity.elements: xsd_fields = identity.elements[xsd_element] if xsd_fields is None: xsd_fields = identity.get_fields(xsd_element.xpath_node) identity.elements[xsd_element] = xsd_fields else: xsd_fields = identity.get_fields(xsd_element.xpath_node) if all(x is None for x in xsd_fields): continue decoders = cast(Tuple[XsdAttribute, ...], xsd_fields) fields = identity.get_fields(element_node, namespaces, decoders=decoders) except (XMLSchemaValueError, XMLSchemaTypeError) as err: yield self.validation_error(validation, err, obj, **kwargs) else: if any(x is not None for x in fields) or nilled: try: counter.increase(fields) except ValueError as err: yield self.validation_error(validation, err, obj, **kwargs) def to_objects(self, obj: ElementType, with_bindings: bool = False, **kwargs: Any) \ -> DecodeType['dataobjects.DataElement']: """ Decodes XML data to Python data objects. :param obj: the XML data source. :param with_bindings: if `True` is provided the decoding is done using \ :class:`DataBindingConverter` that used XML data binding classes. For \ default the objects are instances of :class:`DataElement` and uses the \ :class:`DataElementConverter`. :param kwargs: other optional keyword arguments for the method \ :func:`iter_decode`, except the argument *converter*. """ if with_bindings: return self.decode(obj, converter=dataobjects.DataBindingConverter, **kwargs) return self.decode(obj, converter=dataobjects.DataElementConverter, **kwargs) def iter_encode(self, obj: Any, validation: str = 'lax', **kwargs: Any) \ -> IterEncodeType[ElementType]: """ Creates an iterator for encoding data to an Element. :param obj: the data that has to be encoded. :param validation: the validation mode: can be 'lax', 'strict' or 'skip'. :param kwargs: keyword arguments for the encoding process. :return: yields an Element, eventually preceded by a sequence of \ validation or encoding errors. """ errors: List[Union[str, Exception]] = [] try: converter = kwargs['converter'] except KeyError: converter = self._get_converter(obj, kwargs) else: if not isinstance(converter, XMLSchemaConverter): converter = self._get_converter(obj, kwargs) try: level = kwargs['level'] except KeyError: level = kwargs['level'] = 0 try: element_data = converter.element_encode(obj, self, level) except (ValueError, TypeError) as err: yield self.validation_error(validation, err, obj, **kwargs) return if 'max_depth' in kwargs and kwargs['max_depth'] == 0 and not level: for e in errors: yield self.validation_error(validation, e, **kwargs) return text = None children = element_data.content attributes = () xsd_type = self.get_type(element_data) if XSI_TYPE in element_data.attributes and self.schema.meta_schema is not None: type_name = element_data.attributes[XSI_TYPE].strip() try: xsd_type = self.maps.get_instance_type(type_name, xsd_type, converter) except (KeyError, TypeError) as err: errors.append(err) else: default_namespace = converter.get('') if default_namespace and not isinstance(xsd_type, XsdSimpleType): # Adjust attributes mapped into default namespace ns_part = f'{{{default_namespace}}}' for k in list(element_data.attributes): if not k.startswith(ns_part): continue elif k in xsd_type.attributes: continue local_name = k[len(ns_part):] if local_name in xsd_type.attributes: element_data.attributes[local_name] = element_data.attributes[k] del element_data.attributes[k] attribute_group = self.get_attributes(xsd_type) result: Any for result in attribute_group.iter_encode(element_data.attributes, validation, **kwargs): if isinstance(result, XMLSchemaValidationError): errors.append(result) else: attributes = result if XSI_NIL in element_data.attributes: xsi_nil = element_data.attributes[XSI_NIL].strip() if not self.nillable: errors.append("element is not nillable.") elif xsi_nil not in ('0', '1', 'true', 'false'): errors.append("xsi:nil attribute must has a boolean value.") elif xsi_nil in ('0', 'false'): pass elif self.fixed is not None: errors.append("xsi:nil='true' but the element has a fixed value.") elif element_data.text not in (None, '') or element_data.content: errors.append("xsi:nil='true' but the element is not empty.") else: elem = converter.etree_element(element_data.tag, attrib=attributes, level=level) for e in errors: yield self.validation_error(validation, e, elem, **kwargs) yield elem return if isinstance(xsd_type, XsdSimpleType): if element_data.content: errors.append("a simpleType element can't has child elements.") if element_data.text is not None: for result in xsd_type.iter_encode(element_data.text, validation, **kwargs): if isinstance(result, XMLSchemaValidationError): errors.append(result) else: text = result elif self.fixed is not None: text = self.fixed elif self.default is not None and kwargs.get('use_defaults', True): text = self.default elif xsd_type.has_simple_content(): if element_data.text is not None: for result in xsd_type.content.iter_encode(element_data.text, validation, **kwargs): if isinstance(result, XMLSchemaValidationError): errors.append(result) else: text = result elif self.fixed is not None: text = self.fixed elif self.default is not None and kwargs.get('use_defaults', True): text = self.default else: for result in xsd_type.content.iter_encode(element_data, validation, **kwargs): if isinstance(result, XMLSchemaValidationError): errors.append(result) elif result: text, children = result elem = converter.etree_element(element_data.tag, text, children, attributes, level) if errors: for e in errors: yield self.validation_error(validation, e, elem, **kwargs) yield elem del element_data def is_matching(self, name: Optional[str], default_namespace: Optional[str] = None, group: Optional['XsdGroup'] = None, **kwargs: Any) -> bool: if not name: return False elif default_namespace and name[0] != '{': name = f'{{{default_namespace}}}{name}' # Workaround for backward compatibility of XPath selectors on schemas. if not self.qualified and default_namespace == self.target_namespace: return (name == self.qualified_name or any(name == e.qualified_name for e in self.iter_substitutes())) return name == self.name or any(name == e.name for e in self.iter_substitutes()) def match(self, name: Optional[str], default_namespace: Optional[str] = None, **kwargs: Any) -> Optional['XsdElement']: if not name: return None elif default_namespace and name[0] != '{': name = f'{{{default_namespace}}}{name}' if name == self.name: return self else: for xsd_element in self.iter_substitutes(): if name == xsd_element.name: return xsd_element return None def match_child(self, name: str) -> Optional['XsdElement']: xsd_group = self.type.model_group if xsd_group is None: # fallback to xs:anyType encoder for matching extra content xsd_group = self.any_type.model_group assert xsd_group is not None for xsd_child in xsd_group.iter_elements(): matched_element = xsd_child.match(name, resolve=True) if isinstance(matched_element, XsdElement): return matched_element else: if name in self.maps.elements and xsd_group.open_content_mode != 'none': return self.maps.lookup_element(name) return None def is_restriction(self, other: ModelParticleType, check_occurs: bool = True) -> bool: e: ModelParticleType if isinstance(other, XsdAnyElement): if self.min_occurs == self.max_occurs == 0: return True if check_occurs and not self.has_occurs_restriction(other): return False return other.is_matching(self.name, self.default_namespace) elif isinstance(other, XsdElement): if self.name != other.name: if other.name == self.substitution_group and \ other.min_occurs != other.max_occurs and \ self.max_occurs != 0 and not other.abstract \ and self.xsd_version == '1.0': # A UPA violation case. Base is the head element, it's not # abstract and has non-deterministic occurs: this is less # restrictive than W3C test group (elemZ026), marked as # invalid despite it's based on an abstract declaration. # See also test case invalid_restrictions1.xsd. return False for e in other.iter_substitutes(): if e.name == self.name: break else: return False if check_occurs and not self.has_occurs_restriction(other): return False elif self.max_occurs == 0 and check_occurs: return True # type is not effective if the element can't have occurrences elif not self.is_consistent(other) and self.type.elem is not other.type.elem and \ not self.type.is_derived(other.type, 'restriction') and not other.type.abstract: return False elif other.fixed is not None and \ (self.fixed is None or self.type.normalize( self.fixed) != other.type.normalize(other.fixed)): return False elif other.nillable is False and self.nillable: return False elif any(value not in self.block for value in other.block.split()): return False elif not all(k in other.identities for k in self.identities): return False else: return True elif other.model == 'choice': if other.is_empty() and self.max_occurs != 0: return False check_group_items_occurs = self.xsd_version == '1.0' total_occurs = OccursCalculator() for e in other.iter_model(): if not isinstance(e, (XsdElement, XsdAnyElement)): return False elif not self.is_restriction(e, check_group_items_occurs): continue total_occurs += e total_occurs *= other if self.has_occurs_restriction(total_occurs): return True total_occurs.reset() return False else: match_restriction = False for e in other.iter_model(): if match_restriction: if not e.is_emptiable(): return False elif self.is_restriction(e): match_restriction = True elif not e.is_emptiable(): return False return True def is_overlap(self, other: SchemaElementType) -> bool: if isinstance(other, XsdElement): if self.name == other.name: return True elif other.substitution_group == self.name or other.name == self.substitution_group: return True elif isinstance(other, XsdAnyElement): if other.is_matching(self.name, self.default_namespace): return True for e in self.maps.substitution_groups.get(self.name, ()): if other.is_matching(e.name, self.default_namespace): return True return False def is_consistent(self, other: SchemaElementType, strict: bool = True) -> bool: """ Element Declarations Consistent check between two element particles. Ref: https://www.w3.org/TR/xmlschema-1/#cos-element-consistent :returns: `True` if there is no inconsistency between the particles, `False` otherwise, """ return self.name != other.name or self.type is other.type def is_single(self) -> bool: if self.parent is None: return True elif self.max_occurs != 1: return False elif self.parent.max_occurs == 1: return True else: return self.parent.model != 'choice' and len(self.parent) > 1
(elem: Optional[~T], schema: Optional[~T], parent: Optional[xmlschema.validators.xsdbase.XsdComponent] = None, build: bool = True) -> None
713,808
xmlschema.validators.elements
__init__
null
def __init__(self, elem: ElementType, schema: SchemaType, parent: Optional[XsdComponent] = None, build: bool = True) -> None: if not build: self._build = False self.selected_by = set() super().__init__(elem, schema, parent)
(self, elem: Optional[~T], schema: Optional[~T], parent: Optional[xmlschema.validators.xsdbase.XsdComponent] = None, build: bool = True) -> NoneType
713,809
xmlschema.validators.elements
__iter__
null
def __iter__(self) -> Iterator[SchemaElementType]: if self.type.has_complex_content(): yield from self.type.content.iter_elements() # type: ignore[union-attr]
(self) -> Iterator[Optional[~T]]
713,811
xmlschema.validators.elements
__repr__
null
def __repr__(self) -> str: return '%s(%s=%r, occurs=%r)' % ( self.__class__.__name__, 'name' if self.ref is None else 'ref', self.prefixed_name, list(self.occurs) )
(self) -> str
713,813
xmlschema.validators.elements
__setattr__
null
def __setattr__(self, name: str, value: Any) -> None: if name == "type": if isinstance(value, XsdSimpleType): self.attributes = self.schema.create_empty_attribute_group(self) else: self.attributes = value.attributes super().__setattr__(name, value)
(self, name: str, value: Any) -> NoneType
713,816
xmlschema.validators.elements
_parse
null
def _parse(self) -> None: if not self._build: return self._parse_particle(self.elem) self._parse_attributes() if self.ref is None: self._parse_type() self._parse_constraints() if self.parent is None and 'substitutionGroup' in self.elem.attrib: self._parse_substitution_group(self.elem.attrib['substitutionGroup'])
(self) -> NoneType
713,817
xmlschema.validators.elements
_parse_attributes
null
def _parse_attributes(self) -> None: attrib = self.elem.attrib if self._parse_reference(): try: xsd_element: XsdElement = self.maps.lookup_element(self.name) except KeyError: self.type = self.any_type self.parse_error(_('unknown element %r') % self.name) else: self.ref = xsd_element self.type = xsd_element.type self.abstract = xsd_element.abstract self.nillable = xsd_element.nillable self.qualified = xsd_element.qualified self.form = xsd_element.form self.default = xsd_element.default self.fixed = xsd_element.fixed self.substitution_group = xsd_element.substitution_group self.identities = xsd_element.identities self.alternatives = xsd_element.alternatives self.selected_by = xsd_element.selected_by for attr_name in ('type', 'nillable', 'default', 'fixed', 'form', 'block', 'abstract', 'final', 'substitutionGroup'): if attr_name in attrib: msg = _("attribute {!r} is not allowed when element reference is used") self.parse_error(msg.format(attr_name)) return if 'form' in attrib: self.form = attrib['form'] if self.form == 'qualified': self.qualified = True elif self.schema.element_form_default == 'qualified': self.qualified = True try: if self.parent is None or self.qualified: self.name = get_qname(self.target_namespace, attrib['name']) else: self.name = attrib['name'] except KeyError: pass if 'abstract' in attrib: if self.parent is not None: msg = _("local scope elements cannot have abstract attribute") self.parse_error(msg) if attrib['abstract'].strip() in ('true', '1'): self.abstract = True if 'block' in attrib: try: self._block = get_xsd_derivation_attribute( self.elem, 'block', XSD_ELEMENT_DERIVATIONS ) except ValueError as err: self.parse_error(err) if 'nillable' in attrib and attrib['nillable'].strip() in ('true', '1'): self.nillable = True if self.parent is None: if 'final' in attrib: try: self._final = get_xsd_derivation_attribute( self.elem, 'final', XSD_TYPE_DERIVATIONS ) except ValueError as err: self.parse_error(err) for attr_name in ('ref', 'form', 'minOccurs', 'maxOccurs'): if attr_name in attrib: msg = _("attribute {!r} is not allowed in a global element declaration") self.parse_error(msg.format(attr_name)) else: for attr_name in ('final', 'substitutionGroup'): if attr_name in attrib: msg = _("attribute {!r} not allowed in a local element declaration") self.parse_error(msg.format(attr_name))
(self) -> NoneType
713,819
xmlschema.validators.elements
_parse_constraints
null
def _parse_constraints(self) -> None: # Value constraints if 'default' in self.elem.attrib: self.default = self.elem.attrib['default'] if 'fixed' in self.elem.attrib: msg = _("'default' and 'fixed' attributes are mutually exclusive") self.parse_error(msg) if not self.type.is_valid(self.default): msg = _("'default' value {!r} is not compatible with element's type") self.parse_error(msg.format(self.default)) self.default = None elif self.xsd_version == '1.0' and self.type.is_key(): msg = _("xs:ID or a type derived from xs:ID cannot have a default value") self.parse_error(msg) elif 'fixed' in self.elem.attrib: self.fixed = self.elem.attrib['fixed'] if not self.type.is_valid(self.fixed): msg = _("'fixed' value {!r} is not compatible with element's type") self.parse_error(msg.format(self.fixed)) self.fixed = None elif self.xsd_version == '1.0' and self.type.is_key(): msg = _("xs:ID or a type derived from xs:ID cannot have a fixed value") self.parse_error(msg) # Identity constraints self.identities = [] constraint: Union[XsdKey, XsdUnique, XsdKeyref] for child in self.elem: if child.tag == XSD_UNIQUE: constraint = self.schema.xsd_unique_class(child, self.schema, self) elif child.tag == XSD_KEY: constraint = self.schema.xsd_key_class(child, self.schema, self) elif child.tag == XSD_KEYREF: constraint = self.schema.xsd_keyref_class(child, self.schema, self) else: # Invalid tags already caught by validation against the meta-schema continue if constraint.ref: if any(constraint.name == x.name for x in self.identities): msg = _("duplicated identity constraint %r:") self.parse_error(msg % constraint.name, child) self.identities.append(constraint) continue try: if child != self.maps.identities[constraint.name].elem: msg = _("duplicated identity constraint %r:") self.parse_error(msg % constraint.name, child) except KeyError: self.maps.identities[constraint.name] = constraint finally: self.identities.append(constraint)
(self) -> NoneType
713,820
xmlschema.validators.particles
_parse_particle
null
def _parse_particle(self, elem: ElementType) -> None: if 'minOccurs' in elem.attrib: try: min_occurs = int(elem.attrib['minOccurs']) except (TypeError, ValueError): msg = _("minOccurs value is not an integer value") self.parse_error(msg) else: if min_occurs < 0: msg = _("minOccurs value must be a non negative integer") self.parse_error(msg) else: self.min_occurs = min_occurs max_occurs = elem.get('maxOccurs') if max_occurs is None: if self.min_occurs > 1: msg = _("minOccurs must be lesser or equal than maxOccurs") self.parse_error(msg) elif max_occurs == 'unbounded': self.max_occurs = None else: try: self.max_occurs = int(max_occurs) except ValueError: msg = _("maxOccurs value must be a non negative integer or 'unbounded'") self.parse_error(msg) else: if self.min_occurs > self.max_occurs: msg = _("maxOccurs must be 'unbounded' or greater than minOccurs") self.parse_error(msg) self.max_occurs = None
(self, elem: Optional[~T]) -> NoneType
713,822
xmlschema.validators.elements
_parse_substitution_group
null
def _parse_substitution_group(self, substitution_group: str) -> None: try: substitution_group_qname = self.schema.resolve_qname(substitution_group) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) return else: if substitution_group_qname[0] != '{': substitution_group_qname = get_qname( self.target_namespace, substitution_group_qname ) try: head_element = self.maps.lookup_element(substitution_group_qname) except KeyError: msg = _("unknown substitutionGroup %r") self.parse_error(msg % substitution_group) return else: if isinstance(head_element, tuple): msg = _("circularity found for substitutionGroup %r") self.parse_error(msg % substitution_group) return elif 'substitution' in head_element.block: return final = head_element.final if self.type == head_element.type: pass elif self.type.name == XSD_ANY_TYPE: if head_element.type.name != XSD_ANY_TYPE: # Use head element's type for validate content # ref: https://www.w3.org/TR/xmlschema-1/#cElement_Declarations self._head_type = head_element.type elif not self.type.is_derived(head_element.type): msg = _("{0!r} type is not of the same or a derivation " "of the head element {1!r} type") self.parse_error(msg.format(self, head_element)) elif final == '#all' or 'extension' in final and 'restriction' in final: msg = _("head element %r can't be substituted by an " "element that has a derivation of its type") self.parse_error(msg % head_element) elif 'extension' in final and self.type.is_derived(head_element.type, 'extension'): msg = _("head element %r can't be substituted by an " "element that has an extension of its type") self.parse_error(msg % head_element) elif 'restriction' in final and self.type.is_derived(head_element.type, 'restriction'): msg = _("head element %r can't be substituted by an " "element that has a restriction of its type") self.parse_error(msg % head_element) try: self.maps.substitution_groups[substitution_group_qname].add(self) except KeyError: self.maps.substitution_groups[substitution_group_qname] = {self} finally: self.substitution_group = substitution_group_qname
(self, substitution_group: str) -> NoneType
713,824
xmlschema.validators.elements
_parse_type
null
def _parse_type(self) -> None: type_name = self.elem.get('type') if type_name is not None: try: extended_name = self.schema.resolve_qname(type_name) except (KeyError, ValueError, RuntimeError) as err: self.parse_error(err) self.type = self.any_type else: if extended_name == XSD_ANY_TYPE: self.type = self.any_type else: try: self.type = self.maps.lookup_type(extended_name) except KeyError: self.parse_error(_('unknown type {!r}').format(type_name)) self.type = self.any_type finally: child = self._parse_child_component(self.elem, strict=False) if child is not None and child.tag in (XSD_COMPLEX_TYPE, XSD_SIMPLE_TYPE): msg = _("the attribute 'type' and a xs:{} local " "declaration are mutually exclusive") self.parse_error(msg.format(child.tag.split('}')[-1])) else: child = self._parse_child_component(self.elem, strict=False) if child is None: self.type = self.any_type elif child.tag == XSD_COMPLEX_TYPE: self.type = self.schema.xsd_complex_type_class(child, self.schema, self) elif child.tag == XSD_SIMPLE_TYPE: self.type = self.schema.simple_type_factory(child, self.schema, self) else: self.type = self.any_type
(self) -> NoneType
713,826
xmlschema.validators.elements
build
null
def build(self) -> None: if self._build: return None self._build = True self._parse()
(self) -> NoneType
713,827
xmlschema.validators.elements
check_dynamic_context
null
def check_dynamic_context(self, elem: ElementType, validation: str, options: Dict[str, Any]) -> Iterator[XMLSchemaValidationError]: try: source: XMLResource = options['source'] except KeyError: return for ns, url in etree_iter_location_hints(elem): base_url = source.base_url url = normalize_url(url, base_url) if any(url == schema.url for schema in self.maps.iter_schemas()): continue if ns in etree_iter_namespaces(source.root, elem): reason = _("schemaLocation declaration after namespace start") yield self.validation_error(validation, reason, elem, **options) try: if ns in self.maps.namespaces: schema = self.maps.namespaces[ns][0] schema.include_schema(url) self.schema.clear() self.schema.build() else: self.schema.import_schema(ns, url, base_url, build=True) except (XMLSchemaValidationError, ParseError) as err: yield self.validation_error(validation, err, elem, **options) except XMLSchemaParseError as err: yield self.validation_error(validation, err.message, elem, **options) except OSError: continue
(self, elem: Optional[~T], validation: str, options: Dict[str, Any]) -> Iterator[xmlschema.validators.exceptions.XMLSchemaValidationError]
713,828
xmlschema.validators.elements
collect_key_fields
null
def collect_key_fields(self, obj: ElementType, xsd_type: BaseXsdType, validation: str = 'lax', nilled: bool = False, **kwargs: Any) -> Iterator[XMLSchemaValidationError]: element_node: Union[ElementNode, LazyElementNode] xsd_fields: Optional[IdentityCounterType] try: identities = kwargs['identities'] resource = cast(XMLResource, kwargs['source']) except KeyError: # skip identities collect if identity map or XML source are missing return try: namespaces = kwargs['namespaces'] except KeyError: namespaces = None element_node = resource.get_xpath_node(obj) xsd_element = self if self.ref is None else self.ref if xsd_element.type is not xsd_type: xsd_element = _copy(xsd_element) xsd_element.type = xsd_type # Collect field values for identities that refer to this element. for identity in self.selected_by: try: counter = identities[identity] except KeyError: continue else: if not counter.enabled or not identity.elements: continue if counter.elements is None: # Apply selector on Element ancestor for obtain the selected elements root_node = resource.get_xpath_node(counter.elem) context = XPathContext(root_node) assert identity.selector is not None and identity.selector.token is not None counter.elements = set(identity.selector.token.select_results(context)) if obj not in counter.elements: continue try: if xsd_element.type is self.type and xsd_element in identity.elements: xsd_fields = identity.elements[xsd_element] if xsd_fields is None: xsd_fields = identity.get_fields(xsd_element.xpath_node) identity.elements[xsd_element] = xsd_fields else: xsd_fields = identity.get_fields(xsd_element.xpath_node) if all(x is None for x in xsd_fields): continue decoders = cast(Tuple[XsdAttribute, ...], xsd_fields) fields = identity.get_fields(element_node, namespaces, decoders=decoders) except (XMLSchemaValueError, XMLSchemaTypeError) as err: yield self.validation_error(validation, err, obj, **kwargs) else: if any(x is not None for x in fields) or nilled: try: counter.increase(fields) except ValueError as err: yield self.validation_error(validation, err, obj, **kwargs)
(self, obj: Optional[~T], xsd_type: Optional[~T], validation: str = 'lax', nilled: bool = False, **kwargs: Any) -> Iterator[xmlschema.validators.exceptions.XMLSchemaValidationError]
713,831
xmlschema.validators.elements
data_value
Returns the decoded data value of the provided element as XPath fn:data().
def data_value(self, elem: ElementType) -> Optional[AtomicValueType]: """Returns the decoded data value of the provided element as XPath fn:data().""" text = elem.text if text is None: text = self.fixed if self.fixed is not None else self.default if text is None: if self.type.is_valid(''): self.type.text_decode('') return None return self.type.text_decode(text)
(self, elem: Optional[~T]) -> Optional[~T]
713,837
xmlschema.validators.elements
get_attributes
null
def get_attributes(self, xsd_type: BaseXsdType) -> 'XsdAttributeGroup': if not isinstance(xsd_type, XsdSimpleType): return xsd_type.attributes elif xsd_type is self.type: return self.attributes else: return self.schema.create_empty_attribute_group(self)
(self, xsd_type: Optional[~T]) -> 'XsdAttributeGroup'
713,838
xmlschema.validators.elements
get_binding
Gets data object binding for XSD element, creating a new one if it doesn't exist. :param bases: base classes to use for creating the binding class. :param replace_existing: provide `True` to replace an existing binding class. :param attrs: attribute and method definitions for the binding class body.
def get_binding(self, *bases: Type[Any], replace_existing: bool = False, **attrs: Any) \ -> DataBindingType: """ Gets data object binding for XSD element, creating a new one if it doesn't exist. :param bases: base classes to use for creating the binding class. :param replace_existing: provide `True` to replace an existing binding class. :param attrs: attribute and method definitions for the binding class body. """ if self.binding is None or replace_existing: if not bases: bases = (dataobjects.DataElement,) attrs['xsd_element'] = self class_name = '{}Binding'.format(self.local_name.title().replace('_', '')) self.binding = cast(DataBindingType, dataobjects.DataBindingMeta(class_name, bases, attrs)) return self.binding
(self, *bases: Type[Any], replace_existing: bool = False, **attrs: Any) -> Type[xmlschema.dataobjects.DataElement]
713,839
xmlschema.validators.particles
get_expected
null
def get_expected(self, occurs: OccursCounterType) -> List[SchemaElementType]: return [cast(SchemaElementType, self)] if self.min_occurs > occurs[self] else []
(self, occurs: Optional[~T]) -> List[Optional[~T]]