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,195
xmlschema.converters.gdata
element_decode
null
@stackable def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type tag = self.map_qname(data.tag) result_dict = self.dict(t for t in self.map_attributes(data.attributes)) xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) if self._use_namespaces and xmlns: result_dict.update((f'xmlns${k}' if k else 'xmlns', v) for k, v in xmlns) xsd_group = xsd_type.model_group if xsd_group is None or not data.content: if data.text is not None: result_dict['$t'] = data.text else: has_single_group = xsd_group.is_single() for name, item, xsd_child in self.map_content(data.content): if name.startswith('$') and name[1:].isdigit(): result_dict[name] = item continue assert isinstance(item, MutableMapping) and xsd_child is not None item = item[name] if name in result_dict: other = result_dict[name] if not isinstance(other, MutableSequence) or not other: result_dict[name] = self.list([other, item]) elif isinstance(other[0], MutableSequence) or \ not isinstance(item, MutableSequence): other.append(item) else: result_dict[name] = self.list([other, item]) else: if xsd_type.name == XSD_ANY_TYPE or \ has_single_group and xsd_child.is_single(): result_dict[name] = item else: result_dict[name] = self.list([item]) return self.dict([(tag, result_dict)])
(self, data: xmlschema.converters.default.ElementData, xsd_element: 'XsdElement', xsd_type: Optional[~T] = None, level: int = 0) -> Any
713,196
xmlschema.converters.gdata
element_encode
null
@stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: tag = xsd_element.name if not isinstance(obj, MutableMapping): raise XMLSchemaTypeError(f"A dictionary expected, got {type(obj)} instead.") elif len(obj) != 1 or '$t' in obj: element_data = obj else: for k, v in obj.items(): if isinstance(v, MutableMapping): if '$' in k and not k.startswith(('$', '{')): k = k.replace('$', ':') if k == tag or local_name(k) == local_name(tag): element_data = v break else: element_data = obj text = None content: List[Tuple[Union[str, int], Any]] = [] attributes = {} xmlns = self.set_context(element_data, level) for name, value in element_data.items(): if name == '$t': text = value elif name[0] == '$' and name[1:].isdigit(): content.append((int(name[1:]), value)) elif not isinstance(value, (MutableMapping, MutableSequence)): if name == 'xmlns' or name.startswith('xmlns$'): continue # an xmlns declaration ns_name = self.unmap_qname(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])) for item in value: content.append((ns_name, item)) 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) else: if isinstance(value, MutableSequence): # Fallback tentative to an attribute if no element match attr_name = self.unmap_qname(name, xsd_element.attributes) if attr_name in xsd_element.attributes: attributes[attr_name] = value continue content.append((ns_name, value)) return ElementData(tag, text, content, attributes, xmlns)
(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> xmlschema.converters.default.ElementData
713,201
xmlschema.converters.gdata
get_xmlns_from_data
null
def get_xmlns_from_data(self, obj: Any) -> Optional[List[Tuple[str, str]]]: if not self._use_namespaces or not isinstance(obj, MutableMapping): return None xmlns = [] for k, v in obj.items(): if k == 'xmlns': xmlns.append(('', v)) elif k.startswith('xmlns$'): xmlns.append((k[6:], v)) return xmlns
(self, obj: Any) -> Optional[List[Tuple[str, str]]]
713,207
xmlschema.converters.gdata
map_qname
null
def map_qname(self, qname: str) -> str: name = super().map_qname(qname) if name.startswith('{') or ':' not in name: return name else: return name.replace(':', '$')
(self, qname: str) -> str
713,212
xmlschema.converters.gdata
unmap_qname
null
def unmap_qname(self, qname: str, name_table: Optional[Container[Optional[str]]] = None, xmlns: Optional[List[Tuple[str, str]]] = None) -> str: if '$' in qname and not qname.startswith('$'): qname = qname.replace('$', ':') return super().unmap_qname(qname, name_table, xmlns)
(self, qname: str, name_table: Optional[Container[Optional[str]]] = None, xmlns: Optional[List[Tuple[str, str]]] = None) -> str
713,215
xmlschema.converters.jsonml
JsonMLConverter
XML Schema based converter class for JsonML (JSON Mark-up Language) convention. ref: http://www.jsonml.org/ ref: https://www.ibm.com/developerworks/library/x-jsonml/ :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`.
class JsonMLConverter(XMLSchemaConverter): """ XML Schema based converter class for JsonML (JSON Mark-up Language) convention. ref: http://www.jsonml.org/ ref: https://www.ibm.com/developerworks/library/x-jsonml/ :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`. """ __slots__ = () def __init__(self, namespaces: Optional[NamespacesType] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, **kwargs: Any) -> None: kwargs.update(attr_prefix='', text_key='', cdata_prefix='') super().__init__(namespaces, dict_class, list_class, **kwargs) @property def lossy(self) -> bool: return False @property def losslessly(self) -> bool: return True def get_xmlns_from_data(self, obj: Any) -> Optional[List[Tuple[str, str]]]: if not self._use_namespaces or not isinstance(obj, MutableSequence) \ or len(obj) < 2 or not isinstance(obj[1], MutableMapping): return None xmlns = [] for k, v in obj[1].items(): if k == 'xmlns': xmlns.append(('', v)) elif k.startswith('xmlns:'): xmlns.append((k.split('xmlns:')[1], v)) return xmlns @stackable def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type result_list = self.list() xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) result_list.append(self.map_qname(data.tag)) attributes = self.dict(self.map_attributes(data.attributes)) if xmlns and self._use_namespaces: attributes.update( (f'{self.ns_prefix}:{k}' if k else self.ns_prefix, v) for k, v in xmlns ) if attributes: result_list.append(attributes) if data.text is not None: result_list.append(data.text) if xsd_type.model_group is not None: result_list.extend([ value if value is not None else self.list([name]) for name, value, _ in self.map_content(data.content) ]) return result_list @stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: if not isinstance(obj, MutableSequence): msg = "The first argument must be a sequence, {} provided" raise XMLSchemaTypeError(msg.format(type(obj))) elif not obj: raise XMLSchemaValueError("The first argument is an empty sequence") xmlns = self.set_context(obj, level) data_len = len(obj) if data_len == 1: if not xsd_element.is_matching(self.unmap_qname(obj[0]), self._namespaces.get('')): raise XMLSchemaValueError("Unmatched tag") return ElementData(xsd_element.name, None, None, {}, None) attributes: Dict[str, Any] = {} if isinstance(obj[1], MutableMapping): content_index = 2 for k, v in obj[1].items(): if k != 'xmlns' and not k.startswith('xmlns:'): attributes[self.unmap_qname(k, xsd_element.attributes)] = v else: content_index = 1 if not xsd_element.is_matching(self.unmap_qname(obj[0]), self._namespaces.get('')): raise XMLSchemaValueError("Unmatched tag") if data_len <= content_index: return ElementData(xsd_element.name, None, [], attributes, xmlns) elif data_len == content_index + 1 and \ (xsd_element.type.simple_type is not None or not xsd_element.type.content and xsd_element.type.mixed): return ElementData(xsd_element.name, obj[content_index], [], attributes, xmlns) else: cdata_num = iter(range(1, data_len)) content = [ (self.unmap_qname(e[0], xmlns=self.get_xmlns_from_data(e)), e) if isinstance(e, MutableSequence) else (next(cdata_num), e) for e in obj[content_index:] ] return ElementData(xsd_element.name, None, content, attributes, xmlns)
(namespaces: Optional[~T] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, **kwargs: Any) -> None
713,221
xmlschema.converters.jsonml
__init__
null
def __init__(self, namespaces: Optional[NamespacesType] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, **kwargs: Any) -> None: kwargs.update(attr_prefix='', text_key='', cdata_prefix='') super().__init__(namespaces, dict_class, list_class, **kwargs)
(self, namespaces: Optional[~T] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, **kwargs: Any) -> NoneType
713,228
xmlschema.converters.jsonml
element_decode
null
@stackable def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type result_list = self.list() xmlns = self.get_effective_xmlns(data.xmlns, level, xsd_element) result_list.append(self.map_qname(data.tag)) attributes = self.dict(self.map_attributes(data.attributes)) if xmlns and self._use_namespaces: attributes.update( (f'{self.ns_prefix}:{k}' if k else self.ns_prefix, v) for k, v in xmlns ) if attributes: result_list.append(attributes) if data.text is not None: result_list.append(data.text) if xsd_type.model_group is not None: result_list.extend([ value if value is not None else self.list([name]) for name, value, _ in self.map_content(data.content) ]) return result_list
(self, data: xmlschema.converters.default.ElementData, xsd_element: 'XsdElement', xsd_type: Optional[~T] = None, level: int = 0) -> Any
713,229
xmlschema.converters.jsonml
element_encode
null
@stackable def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: if not isinstance(obj, MutableSequence): msg = "The first argument must be a sequence, {} provided" raise XMLSchemaTypeError(msg.format(type(obj))) elif not obj: raise XMLSchemaValueError("The first argument is an empty sequence") xmlns = self.set_context(obj, level) data_len = len(obj) if data_len == 1: if not xsd_element.is_matching(self.unmap_qname(obj[0]), self._namespaces.get('')): raise XMLSchemaValueError("Unmatched tag") return ElementData(xsd_element.name, None, None, {}, None) attributes: Dict[str, Any] = {} if isinstance(obj[1], MutableMapping): content_index = 2 for k, v in obj[1].items(): if k != 'xmlns' and not k.startswith('xmlns:'): attributes[self.unmap_qname(k, xsd_element.attributes)] = v else: content_index = 1 if not xsd_element.is_matching(self.unmap_qname(obj[0]), self._namespaces.get('')): raise XMLSchemaValueError("Unmatched tag") if data_len <= content_index: return ElementData(xsd_element.name, None, [], attributes, xmlns) elif data_len == content_index + 1 and \ (xsd_element.type.simple_type is not None or not xsd_element.type.content and xsd_element.type.mixed): return ElementData(xsd_element.name, obj[content_index], [], attributes, xmlns) else: cdata_num = iter(range(1, data_len)) content = [ (self.unmap_qname(e[0], xmlns=self.get_xmlns_from_data(e)), e) if isinstance(e, MutableSequence) else (next(cdata_num), e) for e in obj[content_index:] ] return ElementData(xsd_element.name, None, content, attributes, xmlns)
(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> xmlschema.converters.default.ElementData
713,234
xmlschema.converters.jsonml
get_xmlns_from_data
null
def get_xmlns_from_data(self, obj: Any) -> Optional[List[Tuple[str, str]]]: if not self._use_namespaces or not isinstance(obj, MutableSequence) \ or len(obj) < 2 or not isinstance(obj[1], MutableMapping): return None xmlns = [] for k, v in obj[1].items(): if k == 'xmlns': xmlns.append(('', v)) elif k.startswith('xmlns:'): xmlns.append((k.split('xmlns:')[1], v)) return xmlns
(self, obj: Any) -> Optional[List[Tuple[str, str]]]
713,248
xmlschema.converters.parker
ParkerConverter
XML Schema based converter class for Parker convention. ref: http://wiki.open311.org/JSON_and_XML_Conversion/#the-parker-convention ref: https://developer.mozilla.org/en-US/docs/Archive/JXON#The_Parker_Convention :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 preserve_root: If `True` the root element will be preserved. For default the Parker convention remove the document root element, returning only the value.
class ParkerConverter(XMLSchemaConverter): """ XML Schema based converter class for Parker convention. ref: http://wiki.open311.org/JSON_and_XML_Conversion/#the-parker-convention ref: https://developer.mozilla.org/en-US/docs/Archive/JXON#The_Parker_Convention :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 preserve_root: If `True` the root element will be preserved. For default \ the Parker convention remove the document root element, returning only the value. """ __slots__ = () def __init__(self, namespaces: Optional[NamespacesType] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, preserve_root: bool = False, **kwargs: Any) -> None: kwargs.update(attr_prefix=None, text_key='', cdata_prefix=None) super().__init__( namespaces, dict_class, list_class, preserve_root=preserve_root, **kwargs ) @property def xmlns_processing_default(self) -> str: return 'stacked' if isinstance(self.source, XMLResource) else 'none' @property def lossy(self) -> bool: return True @property def loss_xmlns(self) -> bool: return True def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type preserve_root = self.preserve_root if xsd_type.model_group is None or not data.content: if preserve_root: return self.dict([(self.map_qname(data.tag), data.text)]) else: return data.text else: result_dict = self.dict() for name, value, xsd_child in self.map_content(data.content): if preserve_root: try: if len(value) == 1: value = value[name] except (TypeError, KeyError): pass try: result_dict[name].append(value) except KeyError: if isinstance(value, MutableSequence): result_dict[name] = self.list([value]) else: result_dict[name] = value except AttributeError: result_dict[name] = self.list([result_dict[name], value]) for k, v in result_dict.items(): if isinstance(v, MutableSequence) and len(v) == 1: value = v.pop() v.extend(value) if preserve_root: return self.dict([(self.map_qname(data.tag), result_dict)]) else: return result_dict if result_dict else None def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: name: str = xsd_element.name if not isinstance(obj, MutableMapping): if obj == '': obj = None if xsd_element.type.simple_type is not None: return ElementData(xsd_element.name, obj, None, {}, None) else: return ElementData(xsd_element.name, None, obj, {}, None) else: if not obj: return ElementData(xsd_element.name, None, None, {}, None) elif self.preserve_root: try: items = obj[self.map_qname(name)] except KeyError: return ElementData(xsd_element.name, None, None, {}, None) else: items = obj try: content = [] for name, value in obj.items(): ns_name = self.unmap_qname(name) if not isinstance(value, MutableSequence) or not value: content.append((ns_name, value)) elif any(isinstance(v, MutableSequence) for v in value): for item in value: content.append((ns_name, item)) 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) else: content.extend((ns_name, item) for item in value) except AttributeError: return ElementData(xsd_element.name, items, None, {}, None) else: return ElementData(xsd_element.name, None, content, {}, None)
(namespaces: Optional[~T] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, preserve_root: bool = False, **kwargs: Any) -> None
713,254
xmlschema.converters.parker
__init__
null
def __init__(self, namespaces: Optional[NamespacesType] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, preserve_root: bool = False, **kwargs: Any) -> None: kwargs.update(attr_prefix=None, text_key='', cdata_prefix=None) super().__init__( namespaces, dict_class, list_class, preserve_root=preserve_root, **kwargs )
(self, namespaces: Optional[~T] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, preserve_root: bool = False, **kwargs: Any) -> NoneType
713,261
xmlschema.converters.parker
element_decode
null
def element_decode(self, data: ElementData, xsd_element: 'XsdElement', xsd_type: Optional[BaseXsdType] = None, level: int = 0) -> Any: xsd_type = xsd_type or xsd_element.type preserve_root = self.preserve_root if xsd_type.model_group is None or not data.content: if preserve_root: return self.dict([(self.map_qname(data.tag), data.text)]) else: return data.text else: result_dict = self.dict() for name, value, xsd_child in self.map_content(data.content): if preserve_root: try: if len(value) == 1: value = value[name] except (TypeError, KeyError): pass try: result_dict[name].append(value) except KeyError: if isinstance(value, MutableSequence): result_dict[name] = self.list([value]) else: result_dict[name] = value except AttributeError: result_dict[name] = self.list([result_dict[name], value]) for k, v in result_dict.items(): if isinstance(v, MutableSequence) and len(v) == 1: value = v.pop() v.extend(value) if preserve_root: return self.dict([(self.map_qname(data.tag), result_dict)]) else: return result_dict if result_dict else None
(self, data: xmlschema.converters.default.ElementData, xsd_element: 'XsdElement', xsd_type: Optional[~T] = None, level: int = 0) -> Any
713,262
xmlschema.converters.parker
element_encode
null
def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData: name: str = xsd_element.name if not isinstance(obj, MutableMapping): if obj == '': obj = None if xsd_element.type.simple_type is not None: return ElementData(xsd_element.name, obj, None, {}, None) else: return ElementData(xsd_element.name, None, obj, {}, None) else: if not obj: return ElementData(xsd_element.name, None, None, {}, None) elif self.preserve_root: try: items = obj[self.map_qname(name)] except KeyError: return ElementData(xsd_element.name, None, None, {}, None) else: items = obj try: content = [] for name, value in obj.items(): ns_name = self.unmap_qname(name) if not isinstance(value, MutableSequence) or not value: content.append((ns_name, value)) elif any(isinstance(v, MutableSequence) for v in value): for item in value: content.append((ns_name, item)) 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) else: content.extend((ns_name, item) for item in value) except AttributeError: return ElementData(xsd_element.name, items, None, {}, None) else: return ElementData(xsd_element.name, None, content, {}, None)
(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> xmlschema.converters.default.ElementData
713,281
xmlschema.converters.unordered
UnorderedConverter
Same as :class:`XMLSchemaConverter` but :meth:`XMLSchemaConverter.element_encode` returns a dictionary for the content of the element, that can be used directly for unordered encoding mode. In this mode the order of the elements in the encoded output is based on the model visitor pattern rather than the order in which the elements were added to the input dictionary. As the order of the input dictionary is not preserved, character data between sibling elements are interleaved between tags.
class UnorderedConverter(XMLSchemaConverter): """ Same as :class:`XMLSchemaConverter` but :meth:`XMLSchemaConverter.element_encode` returns a dictionary for the content of the element, that can be used directly for unordered encoding mode. In this mode the order of the elements in the encoded output is based on the model visitor pattern rather than the order in which the elements were added to the input dictionary. As the order of the input dictionary is not preserved, character data between sibling elements are interleaved between tags. """ __slots__ = () @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 attributes = {} # The unordered encoding mode assumes that the values of this dict will # all be lists where each item is the content of a single element. When # building content_lu, content which is not a list or lists to be placed # into a single element (element has a list content type) must be wrapped # in a list to retain that structure. Character data are not wrapped into # lists because they are divided from the rest of the content into the # unordered mode generator function of the ModelVisitor class. content_lu: Dict[Union[int, str], Any] = {} 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_lu[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_lu[ns_name] = [value] elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value[0])) content_lu[ns_name] = value else: # `value` is a list but not a list of lists or list of dicts. 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_lu[ns_name] = [value] else: content_lu[ns_name] = value elif self.attr_prefix == '' and ns_name in xsd_element.attributes: attributes[ns_name] = value else: content_lu[ns_name] = value return ElementData(xsd_element.name, text, content_lu, 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,287
xmlschema.converters.default
__init__
null
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 )
(self, namespaces: Optional[~T] = None, dict_class: Optional[Type[Dict[str, Any]]] = None, list_class: Optional[Type[List[Any]]] = None, etree_element_class: Optional[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) -> NoneType
713,294
xmlschema.converters.default
element_decode
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.
@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
(self, data: xmlschema.converters.default.ElementData, xsd_element: 'XsdElement', xsd_type: Optional[~T] = None, level: int = 0) -> Any
713,295
xmlschema.converters.unordered
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 attributes = {} # The unordered encoding mode assumes that the values of this dict will # all be lists where each item is the content of a single element. When # building content_lu, content which is not a list or lists to be placed # into a single element (element has a list content type) must be wrapped # in a list to retain that structure. Character data are not wrapped into # lists because they are divided from the rest of the content into the # unordered mode generator function of the ModelVisitor class. content_lu: Dict[Union[int, str], Any] = {} 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_lu[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_lu[ns_name] = [value] elif isinstance(value[0], (MutableMapping, MutableSequence)): ns_name = self.unmap_qname(name, xmlns=self.get_xmlns_from_data(value[0])) content_lu[ns_name] = value else: # `value` is a list but not a list of lists or list of dicts. 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_lu[ns_name] = [value] else: content_lu[ns_name] = value elif self.attr_prefix == '' and ns_name in xsd_element.attributes: attributes[ns_name] = value else: content_lu[ns_name] = value return ElementData(xsd_element.name, text, content_lu, attributes, xmlns)
(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> xmlschema.converters.default.ElementData
713,314
xmlschema.resources
XMLResource
XML resource reader based on ElementTree and urllib. :param source: a string containing the XML document or file path or a URL or a file like object or an ElementTree or an Element. :param base_url: is an optional base URL, used for the normalization of relative paths when the URL of the resource can't be obtained from the source argument. For security the access to a local file resource is always denied if the *base_url* is a remote URL. :param allow: defines the security mode for accessing resource locations. Can be 'all', 'remote', 'local', 'sandbox' or 'none'. Default is 'all', which 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 the *base_url* argument are allowed. If you provide 'none', no resources will be allowed from any location. :param defuse: defines when to defuse XML data using a `SafeXMLParser`. Can be 'always', 'remote', 'nonlocal' or 'never'. For default defuses only remote XML data. With 'always' all the XML data that is not already parsed is defused. With 'nonlocal' it defuses unparsed data except local files. With 'never' no XML data source is defused. :param timeout: the timeout in seconds for the connection attempt in case of remote data. :param lazy: if a value `False` or 0 is provided the XML data is fully loaded into and processed from memory. For default only the root element of the source is loaded, except in case the *source* argument is an Element or an ElementTree instance. A positive integer also defines the depth at which the lazy resource can be better iterated (`True` means 1). :param thin_lazy: for default, in order to reduce the memory usage, during the iteration of a lazy resource at *lazy_depth* level, deletes also the preceding elements after the use. :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.
class XMLResource: """ XML resource reader based on ElementTree and urllib. :param source: a string containing the XML document or file path or a URL or a \ file like object or an ElementTree or an Element. :param base_url: is an optional base URL, used for the normalization of relative paths \ when the URL of the resource can't be obtained from the source argument. For security \ the access to a local file resource is always denied if the *base_url* is a remote URL. :param allow: defines the security mode for accessing resource locations. Can be \ 'all', 'remote', 'local', 'sandbox' or 'none'. Default is 'all', which 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 the *base_url* argument are allowed. \ If you provide 'none', no resources will be allowed from any location. :param defuse: defines when to defuse XML data using a `SafeXMLParser`. Can be \ 'always', 'remote', 'nonlocal' or 'never'. For default defuses only remote XML data. \ With 'always' all the XML data that is not already parsed is defused. With 'nonlocal' \ it defuses unparsed data except local files. With 'never' no XML data source is defused. :param timeout: the timeout in seconds for the connection attempt in case of remote data. :param lazy: if a value `False` or 0 is provided the XML data is fully loaded into and \ processed from memory. For default only the root element of the source is loaded, \ except in case the *source* argument is an Element or an ElementTree instance. A \ positive integer also defines the depth at which the lazy resource can be better \ iterated (`True` means 1). :param thin_lazy: for default, in order to reduce the memory usage, during the \ iteration of a lazy resource at *lazy_depth* level, deletes also the preceding \ elements after the use. :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. """ # Protected attributes for data and resource location _source: XMLSourceType _root: ElementType _xpath_root: Union[None, ElementNode, DocumentNode] = None _nsmaps: Dict[ElementType, Dict[str, str]] _xmlns: Dict[ElementType, List[Tuple[str, str]]] _text: Optional[str] = None _url: Optional[str] = None _base_url: Optional[str] = None _parent_map: Optional[ParentMapType] = None _lazy: Union[bool, int] = False def __init__(self, source: XMLSourceType, base_url: Union[None, str, Path, bytes] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, lazy: Union[bool, int] = False, thin_lazy: bool = True, uri_mapper: Optional[UriMapperType] = None) -> None: if isinstance(base_url, (str, bytes)): if not is_url(base_url): raise XMLSchemaValueError("'base_url' argument is not an URL") self._base_url = base_url if isinstance(base_url, str) else base_url.decode() elif isinstance(base_url, Path): self._base_url = str(base_url) elif base_url is not None: msg = "invalid type %r for argument 'base_url'" raise XMLSchemaTypeError(msg % type(base_url)) if not isinstance(allow, str): msg = "invalid type %r for argument 'allow'" raise XMLSchemaTypeError(msg % type(allow)) elif allow not in SECURITY_MODES: msg = "'allow' argument: %r is not a security mode" raise XMLSchemaValueError(msg % allow) elif allow == 'sandbox' and self._base_url is None: msg = "block access to files out of sandbox requires 'base_url' to be set" raise XMLResourceError(msg) self._allow = allow if not isinstance(defuse, str): msg = "invalid type %r for argument 'defuse'" raise XMLSchemaTypeError(msg % type(defuse)) elif defuse not in DEFUSE_MODES: msg = "'defuse' argument: %r is not a defuse mode" raise XMLSchemaValueError(msg % defuse) self._defuse = defuse if not isinstance(timeout, int): msg = "invalid type %r for argument 'timeout'" raise XMLSchemaTypeError(msg % type(timeout)) elif timeout <= 0: msg = "the argument 'timeout' must be a positive integer" raise XMLSchemaValueError(msg) self._timeout = timeout if not isinstance(thin_lazy, bool): msg = "invalid type %r for argument 'thin_lazy'" raise XMLSchemaTypeError(msg % type(thin_lazy)) self._thin_lazy = thin_lazy if uri_mapper is not None and not callable(uri_mapper) \ and not isinstance(uri_mapper, MutableMapping): msg = "invalid type %r for argument 'uri_mapper'" raise XMLSchemaTypeError(msg % type(uri_mapper)) self._uri_mapper = uri_mapper self.parse(source, lazy) def __repr__(self) -> str: return '%s(root=%r)' % (self.__class__.__name__, self._root) @property def source(self) -> XMLSourceType: """The XML data source.""" return self._source @property def root(self) -> ElementType: """The XML tree root Element.""" return self._root @property def text(self) -> Optional[str]: """The XML text source, `None` if it's not available.""" return self._text @property def name(self) -> Optional[str]: """ The source name, is `None` if the instance is created from an Element or a string. """ return None if self._url is None else os.path.basename(unquote(self._url)) @property def url(self) -> Optional[str]: """ The source URL, `None` if the instance is created from an Element or a string. """ return self._url @property def base_url(self) -> Optional[str]: """The effective base URL used for completing relative locations.""" return os.path.dirname(self._url) if self._url else self._base_url @property def filepath(self) -> Optional[str]: """ The resource filepath if the instance is created from a local file, `None` otherwise. """ if self._url: url_parts = urlsplit(self._url) if url_parts.scheme in ('', 'file'): return str(LocationPath.from_uri(self._url)) return None @property def allow(self) -> str: """The security mode for accessing resource locations.""" return self._allow @property def defuse(self) -> str: """When to defuse XML data.""" return self._defuse @property def timeout(self) -> int: """The timeout in seconds for accessing remote resources.""" return self._timeout @property def uri_mapper(self) -> Optional[UriMapperType]: """The optional URI mapper argument for relocating addressed resources.""" return self._uri_mapper @property def lazy_depth(self) -> int: """ The depth at which the XML tree of the resource is fully loaded during iterations methods. Is a positive integer for lazy resources and 0 for fully loaded XML trees. """ return int(self._lazy) @property def namespace(self) -> str: """The namespace of the XML resource.""" return get_namespace(self._root.tag) @property def parent_map(self) -> Dict[ElementType, Optional[ElementType]]: if self._lazy: raise XMLResourceError("cannot create the parent map of a lazy XML resource") if self._parent_map is None: self._parent_map = {child: elem for elem in self._root.iter() for child in elem} self._parent_map[self._root] = None return self._parent_map @property def xpath_root(self) -> Union[ElementNode, DocumentNode]: """The XPath root node.""" if self._xpath_root is None: if hasattr(self._root, 'xpath'): self._xpath_root = build_lxml_node_tree(cast(LxmlElementProtocol, self._root)) else: try: _nsmap = self._nsmaps[self._root] except KeyError: # A resource based on an ElementTree structure (no namespace maps) self._xpath_root = build_node_tree(self._root) else: node_tree = build_node_tree(self._root, _nsmap) # Update namespace maps for node in node_tree.iter_descendants(with_self=False): if isinstance(node, ElementNode): nsmap = self._nsmaps[cast(ElementType, node.elem)] node.nsmap = {k or '': v for k, v in nsmap.items()} self._xpath_root = node_tree return self._xpath_root def is_lazy(self) -> bool: """Returns `True` if the XML resource is lazy.""" return bool(self._lazy) def is_thin(self) -> bool: """Returns `True` if the XML resource is lazy and thin.""" return bool(self._lazy) and self._thin_lazy def is_remote(self) -> bool: """Returns `True` if the resource is related with remote XML data.""" return is_remote_url(self._url) def is_local(self) -> bool: """Returns `True` if the resource is related with local XML data.""" return is_local_url(self._url) def is_loaded(self) -> bool: """Returns `True` if the XML text of the data source is loaded.""" return self._text is not None def _access_control(self, url: str) -> None: if self._allow == 'all': return elif self._allow == 'none': raise XMLResourceError(f"block access to resource {url}") elif self._allow == 'remote': if is_local_url(url): raise XMLResourceError(f"block access to local resource {url}") elif is_remote_url(url): raise XMLResourceError(f"block access to remote resource {url}") elif self._allow == 'sandbox' and self._base_url is not None: if not url.startswith(normalize_url(self._base_url)): raise XMLResourceError(f"block access to out of sandbox file {url}") def _lazy_clear(self, elem: ElementType, ancestors: Optional[List[ElementType]] = None) -> None: if ancestors and self._thin_lazy: # Delete preceding elements for parent, child in zip_longest(ancestors, ancestors[1:]): if child is None: child = elem for k, e in enumerate(parent): if child is not e: if e in self._xmlns: del self._xmlns[e] del self._nsmaps[e] else: if k: del parent[:k] break for e in elem.iter(): if elem is not e: if e in self._xmlns: del self._xmlns[e] del self._nsmaps[e] del elem[:] # delete children, keep attributes, text and tail. # reset the whole XPath tree to let it still usable if other # children are added to the root by ElementTree.iterparse(). self.xpath_root.children.clear() def _lazy_iterparse(self, resource: IO[AnyStr]) -> Iterator[Tuple[str, ElementType]]: events: Tuple[str, ...] events = 'start-ns', 'end-ns', 'start', 'end' if self._defuse == 'remote' and is_remote_url(self.base_url) \ or self._defuse == 'nonlocal' and not is_local_url(self.base_url) \ or self._defuse == 'always': safe_parser = SafeXMLParser(target=PyElementTree.TreeBuilder()) tree_iterator = PyElementTree.iterparse(resource, events, safe_parser) else: tree_iterator = ElementTree.iterparse(resource, events) root_started = False start_ns: List[Tuple[str, str]] = [] end_ns = False nsmap_stack: List[Dict[str, str]] = [{}] # Save previous status (if any) _root: Optional[ElementType] _nsmaps: Optional[Dict[ElementType, Dict[str, str]]] _ns_declarations: Optional[Dict[ElementType, List[Tuple[str, str]]]] if hasattr(self, '_root'): _root = self._root _nsmaps = self._nsmaps _ns_declarations = self._xmlns _xpath_root = self._xpath_root else: _root = _nsmaps = _ns_declarations = _xpath_root = None self._nsmaps = {} self._xmlns = {} try: for event, node in tree_iterator: if event == 'start': if end_ns: nsmap_stack.pop() end_ns = False if start_ns: nsmap_stack.append(nsmap_stack[-1].copy()) nsmap_stack[-1].update(start_ns) self._xmlns[node] = start_ns start_ns = [] self._nsmaps[node] = nsmap_stack[-1] if not root_started: self._root = node self._xpath_root = LazyElementNode( self._root, nsmap=self._nsmaps[node] ) root_started = True yield event, node elif event == 'end': if end_ns: nsmap_stack.pop() end_ns = False yield event, node elif event == 'start-ns': start_ns.append(node) else: end_ns = True except Exception as err: if _root is not None \ and _nsmaps is not None \ and _ns_declarations is not None: self._root = _root self._nsmaps = _nsmaps self._xmlns = _ns_declarations self._xpath_root = _xpath_root if isinstance(err, PyElementTree.ParseError): raise ElementTree.ParseError(str(err)) from None raise def _parse(self, resource: IO[AnyStr]) -> None: if self._defuse == 'remote' and is_remote_url(self.base_url) \ or self._defuse == 'nonlocal' and not is_local_url(self.base_url) \ or self._defuse == 'always': if not hasattr(resource, 'seekable') or not resource.seekable(): text = resource.read() if isinstance(text, str): resource = StringIO(text) else: resource = BytesIO(text) safe_parser = SafeXMLParser(target=PyElementTree.TreeBuilder()) try: for _ in PyElementTree.iterparse(resource, ('start',), safe_parser): break except PyElementTree.ParseError as err: raise ElementTree.ParseError(str(err)) else: resource.seek(0) root: Optional[ElementType] = None start_ns: List[Tuple[str, str]] = [] end_ns = False nsmaps: Dict[ElementType, Dict[str, str]] = {} ns_declarations: Dict[ElementType, List[Tuple[str, str]]] = {} events = 'start-ns', 'end-ns', 'start' nsmap_stack: List[Dict[str, str]] = [{}] for event, node in ElementTree.iterparse(resource, events): if event == 'start': if root is None: root = node if end_ns: nsmap_stack.pop() end_ns = False if start_ns: nsmap_stack.append(nsmap_stack[-1].copy()) nsmap_stack[-1].update(start_ns) ns_declarations[node] = start_ns start_ns = [] nsmaps[node] = nsmap_stack[-1] elif event == 'start-ns': start_ns.append(node) else: end_ns = True assert root is not None self._root = root self._xpath_root = None self._nsmaps = nsmaps self._xmlns = ns_declarations def _parse_resource(self, resource: IO[AnyStr], url: Optional[str], lazy: Union[bool, int]) -> None: _url, self._url = self._url, url try: if not lazy: self._parse(resource) else: for _, root in self._lazy_iterparse(resource): # pragma: no cover break except Exception: self._url = _url raise def _get_parsed_url(self, url: str) -> str: if isinstance(self._uri_mapper, MutableMapping): if url in self._uri_mapper: url = self._uri_mapper[url] elif callable(self._uri_mapper): url = self._uri_mapper(url) url = normalize_url(url, self._base_url) self._access_control(url) return url def parse(self, source: XMLSourceType, lazy: Union[bool, int] = False) -> None: if isinstance(lazy, bool): pass elif not isinstance(lazy, int): msg = "invalid type %r for the attribute 'lazy'" raise XMLSchemaTypeError(msg % type(lazy)) elif lazy < 0: msg = "invalid value %r for the attribute 'lazy'" raise XMLSchemaValueError(msg % lazy) url: Optional[str] if isinstance(source, str): if is_url(source): # source is a string containing a URL or a file path url = self._get_parsed_url(source.strip()) with urlopen(url, timeout=self._timeout) as resource: self._parse_resource(resource, url, lazy) self._text = None self._lazy = lazy else: # source is a string containing an XML document resource = StringIO(source) self._parse_resource(resource, None, lazy) self._text = source self._lazy = False elif isinstance(source, bytes): if is_url(source): # source is a byte-string containing a URL or a file path url = self._get_parsed_url(source.decode().strip()) with urlopen(url, timeout=self._timeout) as resource: self._parse_resource(resource, url, lazy) self._text = None self._lazy = lazy else: resource = BytesIO(source) self._parse_resource(resource, None, lazy) self._text = source.decode() self._lazy = False elif isinstance(source, Path): url = self._get_parsed_url(str(source)) with urlopen(url, timeout=self._timeout) as resource: self._parse_resource(resource, url, lazy) self._text = None self._lazy = lazy elif isinstance(source, StringIO): self._parse_resource(source, None, lazy) self._text = source.getvalue() self._lazy = lazy elif hasattr(source, 'read'): # source is a readable resource (remote or local file) url = getattr(source, 'url', None) if url is not None: self._access_control(url) # Save remote urls for open new resources (non seekable) if not is_remote_url(url): url = None self._parse_resource(cast(IO[str], source), url, lazy) self._text = None self._lazy = lazy else: # source is an Element or an ElementTree if hasattr(source, 'tag') and hasattr(source, 'attrib'): # Source is already an Element --> nothing to parse self._root = cast(ElementType, source) elif is_etree_document(source): # Could be only an ElementTree object at last self._root = source.getroot() else: raise XMLSchemaTypeError( "wrong type %r for 'source' attribute: an ElementTree object or " "an Element instance or a string containing XML data or an URL " "or a file-like object is required." % type(source) ) self._xpath_root = None self._text = self._url = None self._lazy = False self._nsmaps = {} self._xmlns = {} if hasattr(self._root, 'xpath'): nsmap = {} lxml_nsmap = None for elem in cast(Any, self._root.iter()): if callable(elem.tag): self._nsmaps[elem] = {} continue if lxml_nsmap != elem.nsmap: nsmap = {k or '': v for k, v in elem.nsmap.items()} lxml_nsmap = elem.nsmap parent = elem.getparent() if parent is None: ns_declarations = [(k or '', v) for k, v in nsmap.items()] elif parent.nsmap != elem.nsmap: ns_declarations = [(k or '', v) for k, v in elem.nsmap.items() if k not in parent.nsmap or v != parent.nsmap[k]] else: ns_declarations = None self._nsmaps[elem] = nsmap if ns_declarations: self._xmlns[elem] = ns_declarations self._parent_map = None self._source = source def get_xpath_node(self, elem: ElementType) -> ElementNode: """ Returns an XPath node for the element, fetching it from the XPath root node. Returns a new lazy element node if the matching element node is not found. """ xpath_node = self.xpath_root.get_element_node(elem) if xpath_node is not None: return xpath_node try: return LazyElementNode(elem, nsmap=self._nsmaps[elem]) except KeyError: return LazyElementNode(elem) def get_nsmap(self, elem: ElementType) -> Optional[Dict[str, str]]: """ Returns the namespace map (nsmap) of the element. Returns `None` if no nsmap is found for the element. Lazy resources have only the nsmap for the root element. """ try: return self._nsmaps[elem] except KeyError: return getattr(elem, 'nsmap', None) # an lxml element def get_xmlns(self, elem: ElementType) -> Optional[List[Tuple[str, str]]]: """ Returns the list of namespaces declarations (xmlns and xmlns:<prefix> attributes) of the element. Returns `None` if the element doesn't have namespace declarations. Lazy resources have only the namespace declarations for the root element. """ return self._xmlns.get(elem) def get_absolute_path(self, path: Optional[str] = None) -> str: if path is None: if self._lazy: return f"/{self._root.tag}/{'/'.join('*' * int(self._lazy))}" return f'/{self._root.tag}' elif path.startswith('/'): return path else: return f'/{self._root.tag}/{path}' def get_text(self) -> str: """ Gets the source text of the XML document. If the source text is not available creates an encoded string representation of the XML tree. Il the resource is lazy raises a resource error. """ if self._text is not None: return self._text elif self._url is not None: self.load() if self._text is not None: return self._text return self.tostring(xml_declaration=True) def tostring(self, namespaces: Optional[MutableMapping[str, str]] = None, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: int = 4, xml_declaration: bool = False, encoding: str = 'unicode', method: str = 'xml') -> str: """ Serialize an XML resource to a string. :param namespaces: is an optional mapping from namespace prefix to URI. \ Provided namespaces are registered before serialization. Ignored if the \ provided *elem* argument is a lxml Element instance. :param indent: the baseline indentation. :param max_lines: if truncate serialization after a number of lines \ (default: do not truncate). :param spaces_for_tab: number of spaces for replacing tab characters. For \ default tabs are replaced with 4 spaces, provide `None` to keep tab characters. :param xml_declaration: if set to `True` inserts the XML declaration at the head. :param encoding: if "unicode" (the default) the output is a string, \ otherwise it’s binary. :param method: is either "xml" (the default), "html" or "text". :return: a Unicode string. """ if self._lazy: raise XMLResourceError("cannot serialize a lazy XML resource") if not hasattr(self._root, 'nsmap'): namespaces = self.get_namespaces(namespaces, root_only=False) _string = etree_tostring( elem=self._root, namespaces=namespaces, indent=indent, max_lines=max_lines, spaces_for_tab=spaces_for_tab, xml_declaration=xml_declaration, encoding=encoding, method=method ) if isinstance(_string, bytes): # pragma: no cover return _string.decode('utf-8') return _string def subresource(self, elem: ElementType) -> 'XMLResource': """Create an XMLResource instance from a subelement of a non-lazy XML tree.""" if self._lazy: raise XMLResourceError("cannot create a subresource from a lazy XML resource") for e in self._root.iter(): # pragma: no cover if e is elem: break else: msg = "{!r} is not an element or the XML resource tree" raise XMLResourceError(msg.format(elem)) resource = XMLResource(elem, self.base_url, self._allow, self._defuse, self._timeout) if not hasattr(elem, 'nsmap'): for e in elem.iter(): resource._nsmaps[e] = self._nsmaps[e] if e is elem: ns_declarations = [(k, v) for k, v in self._nsmaps[e].items()] if ns_declarations: resource._xmlns[e] = ns_declarations elif e in self._xmlns: resource._xmlns[e] = self._xmlns[e] return resource def open(self) -> IO[AnyStr]: """ Returns an opened resource reader object for the instance URL. If the source attribute is a seekable file-like object rewind the source and return it. """ if self.seek(0) == 0: return cast(IO[AnyStr], self._source) elif self._url is None: raise XMLResourceError(f"can't open, {self!r} has no URL associated") try: return cast(IO[AnyStr], urlopen(self._url, timeout=self._timeout)) except URLError as err: msg = "cannot access to resource %(url)r: %(reason)s" raise XMLResourceError(msg % {'url': self._url, 'reason': err.reason}) def seek(self, position: int) -> Optional[int]: """ Change stream position if the XML resource was created with a seekable file-like object. In the other cases this method has no effect. """ if not hasattr(self._source, 'read'): return None try: if not self._source.seekable(): # type: ignore[union-attr] return None except AttributeError: return None # pragma: no cover except ValueError as err: raise XMLResourceError(str(err)) from None else: return self._source.seek(position) # type: ignore[union-attr] def close(self) -> None: """ Close the XML resource if it's created with a file-like object. In other cases this method has no effect. """ try: self._source.close() # type: ignore[union-attr] except (AttributeError, TypeError): pass def load(self) -> None: """ Loads the XML text from the data source. If the data source is an Element the source XML text can't be retrieved. """ if self._url is None and not hasattr(self._source, 'read'): return # Created from Element or text source --> already loaded elif self._lazy: raise XMLResourceError("cannot load a lazy XML resource") resource = self.open() try: data = resource.read() finally: # We don't want to close the file obj if it wasn't originally # opened by `XMLResource`. That is the concern of the code # where the file obj came from. if resource is not self._source: resource.close() if isinstance(data, bytes): try: text = data.decode('utf-8') except UnicodeDecodeError: text = data.decode('iso-8859-1') else: text = data self._text = text def iter(self, tag: Optional[str] = None) -> Iterator[ElementType]: """ XML resource tree iterator. If tag is not None or '*', only elements whose tag equals tag are returned from the iterator. In a lazy resource the yielded elements are full over or at *lazy_depth* level, otherwise are incomplete and thin for default. """ if not self._lazy: yield from self._root.iter(tag) return resource = self.open() tag = '*' if tag is None else tag.strip() lazy_depth = int(self._lazy) subtree_elements: Deque[ElementType] = deque() ancestors = [] level = 0 try: for event, node in self._lazy_iterparse(resource): if event == "start": if level < lazy_depth: if level: ancestors.append(node) if tag == '*' or node.tag == tag: yield node # an incomplete element level += 1 else: level -= 1 if level < lazy_depth: if level: ancestors.pop() continue # pragma: no cover elif level > lazy_depth: if tag == '*' or node.tag == tag: subtree_elements.appendleft(node) continue # pragma: no cover if tag == '*' or node.tag == tag: yield node # a full element yield from subtree_elements subtree_elements.clear() self._lazy_clear(node, ancestors) finally: # Close the resource only if it was originally opened by XMLResource if resource is not self._source: resource.close() def iter_location_hints(self, tag: Optional[str] = None) -> Iterator[Tuple[str, str]]: """ Yields all schema location hints of the XML resource. If tag is not None or '*', only location hints of elements whose tag equals tag are returned from the iterator. """ for elem in self.iter(tag): yield from etree_iter_location_hints(elem) def iter_depth(self, mode: int = 1, ancestors: Optional[List[ElementType]] = None) \ -> Iterator[ElementType]: """ Iterates XML subtrees. For fully loaded resources yields the root element. On lazy resources the argument *mode* can change the sequence and the completeness of yielded elements. There are four possible modes, that generate different sequences of elements:\n 1. Only the elements at *depth_level* level of the tree\n 2. Only the elements at *depth_level* level of the tree removing\n the preceding elements of ancestors (thin lazy tree) 3. Only a root element pruned at *depth_level*\n 4. The elements at *depth_level* and then a pruned root\n 5. An incomplete root at start, the elements at *depth_level* and a pruned root\n :param mode: an integer in range [1..5] that defines the iteration mode. :param ancestors: provide a list for tracking the ancestors of yielded elements. """ if mode not in (1, 2, 3, 4, 5): raise XMLSchemaValueError(f"invalid argument mode={mode!r}") if ancestors is not None: ancestors.clear() elif mode <= 2: ancestors = [] if not self._lazy: yield self._root return resource = self.open() level = 0 lazy_depth = int(self._lazy) # boolean flags incomplete_root = mode == 5 pruned_root = mode > 2 depth_level_elements = mode != 3 thin_lazy = mode <= 2 try: for event, elem in self._lazy_iterparse(resource): if event == "start": if not level: if incomplete_root: yield elem if ancestors is not None and level < lazy_depth: ancestors.append(elem) level += 1 else: level -= 1 if not level: if pruned_root: yield elem continue elif level != lazy_depth: if ancestors is not None and level < lazy_depth: ancestors.pop() continue # pragma: no cover elif depth_level_elements: yield elem if thin_lazy: self._lazy_clear(elem, ancestors) else: self._lazy_clear(elem) finally: if self._source is not resource: resource.close() def _select_elements(self, token: XPathToken, node: ResourceNodeType, ancestors: Optional[List[ElementType]] = None) -> Iterator[ElementType]: context = XPathContext(node) for item in token.select(context): if not isinstance(item, ElementNode): # pragma: no cover msg = "XPath expressions on XML resources can select only elements" raise XMLResourceError(msg) elif ancestors is not None: if item.elem is self._root: ancestors.clear() else: _ancestors: Any = [] parent = item.parent while parent is not None: _ancestors.append(parent.value) parent = parent.parent if _ancestors: ancestors.clear() ancestors.extend(reversed(_ancestors)) yield cast(ElementType, item.elem) def iterfind(self, path: str, namespaces: Optional[NamespacesType] = None, ancestors: Optional[List[ElementType]] = None) -> Iterator[ElementType]: """ Apply XPath selection to XML resource that yields full subtrees. :param path: an XPath 2.0 expression that selects element nodes. \ Selecting other values or nodes raise an error. :param namespaces: an optional mapping from namespace prefixes to URIs \ used for parsing the XPath expression. :param ancestors: provide a list for tracking the ancestors of yielded elements. """ parser = XPath2Parser(namespaces, strict=False) token = parser.parse(path) if not self._lazy: yield from self._select_elements(token, self.xpath_root, ancestors) return resource = self.open() lazy_depth = int(self._lazy) level = 0 path = path.replace(' ', '').replace('./', '') select_all = '*' in path and set(path).issubset(('*', '/')) if path == '.': path_depth = 0 elif path.startswith('/'): path_depth = path.count('/') - 1 else: path_depth = path.count('/') + 1 if not path_depth: raise XMLResourceError(f"cannot use path {path!r} on a lazy resource") elif path_depth < lazy_depth: raise XMLResourceError(f"cannot use path {path!r} on a lazy resource " f"with lazy_depth=={lazy_depth}") if ancestors is not None: ancestors.clear() elif self._thin_lazy: ancestors = [] try: for event, node in self._lazy_iterparse(resource): if event == "start": if ancestors is not None and level < path_depth: ancestors.append(node) level += 1 else: level -= 1 if level < path_depth: if ancestors is not None: ancestors.pop() continue elif level == path_depth: if select_all or \ node in self._select_elements(token, self.xpath_root): yield node if level == lazy_depth: self._lazy_clear(node, ancestors) finally: if self._source is not resource: resource.close() def find(self, path: str, namespaces: Optional[NamespacesType] = None, ancestors: Optional[List[ElementType]] = None) -> Optional[ElementType]: return next(self.iterfind(path, namespaces, ancestors), None) def findall(self, path: str, namespaces: Optional[NamespacesType] = None) \ -> List[ElementType]: return list(self.iterfind(path, namespaces)) def get_namespaces(self, namespaces: Optional[NamespacesType] = None, root_only: bool = True) -> NamespacesType: """ Extracts namespaces with related prefixes from the XML resource. If a duplicate prefix is encountered in a xmlns declaration, and this is mapped to a different namespace, adds the namespace using a different generated prefix. The empty prefix '' is used only if it's declared at root level to avoid erroneous mapping of local names. In other cases it uses the prefix 'default' as substitute. :param namespaces: is an optional mapping from namespace prefix to URI that \ integrate/override the namespace declarations of the root element. :param root_only: if `True` extracts only the namespaces declared in the root \ element, otherwise scan the whole tree for further namespace declarations. \ A full namespace map can be useful for cases where the element context is \ not available. :return: a dictionary for mapping namespace prefixes to full URI. """ namespaces = get_namespace_map(namespaces) try: for elem in self.iter(): if elem in self._xmlns: update_namespaces(namespaces, self._xmlns[elem], elem is self._root) if root_only: break except (ElementTree.ParseError, PyElementTree.ParseError, UnicodeEncodeError): return namespaces # a lazy resource with malformed XML data else: return namespaces def get_locations(self, locations: Optional[LocationsType] = None, root_only: bool = True) -> NormalizedLocationsType: """ Extracts a list of schema location hints from the XML resource. The locations are normalized using the base URL of the instance. :param locations: a sequence of schema location hints inserted \ before the ones extracted from the XML resource. Locations passed \ within a tuple container are not normalized. :param root_only: if `True` extracts only the location hints of the \ root element. :returns: a list of couples containing normalized location hints. """ if not locations: location_hints = [] elif isinstance(locations, tuple): location_hints = [x for x in locations] else: location_hints = normalize_locations(locations, self.base_url) if root_only: location_hints.extend([ (ns, normalize_url(url, self.base_url)) for ns, url in etree_iter_location_hints(self._root) ]) else: try: location_hints.extend([ (ns, normalize_url(url, self.base_url)) for ns, url in self.iter_location_hints() ]) except (ElementTree.ParseError, PyElementTree.ParseError, UnicodeEncodeError): pass # a lazy resource containing malformed XML data after the first tag return location_hints
(source: Optional[~T], base_url: Union[NoneType, str, pathlib.Path, bytes] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, lazy: Union[bool, int] = False, thin_lazy: bool = True, uri_mapper: Optional[~T] = None) -> None
713,315
xmlschema.resources
__init__
null
def __init__(self, source: XMLSourceType, base_url: Union[None, str, Path, bytes] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, lazy: Union[bool, int] = False, thin_lazy: bool = True, uri_mapper: Optional[UriMapperType] = None) -> None: if isinstance(base_url, (str, bytes)): if not is_url(base_url): raise XMLSchemaValueError("'base_url' argument is not an URL") self._base_url = base_url if isinstance(base_url, str) else base_url.decode() elif isinstance(base_url, Path): self._base_url = str(base_url) elif base_url is not None: msg = "invalid type %r for argument 'base_url'" raise XMLSchemaTypeError(msg % type(base_url)) if not isinstance(allow, str): msg = "invalid type %r for argument 'allow'" raise XMLSchemaTypeError(msg % type(allow)) elif allow not in SECURITY_MODES: msg = "'allow' argument: %r is not a security mode" raise XMLSchemaValueError(msg % allow) elif allow == 'sandbox' and self._base_url is None: msg = "block access to files out of sandbox requires 'base_url' to be set" raise XMLResourceError(msg) self._allow = allow if not isinstance(defuse, str): msg = "invalid type %r for argument 'defuse'" raise XMLSchemaTypeError(msg % type(defuse)) elif defuse not in DEFUSE_MODES: msg = "'defuse' argument: %r is not a defuse mode" raise XMLSchemaValueError(msg % defuse) self._defuse = defuse if not isinstance(timeout, int): msg = "invalid type %r for argument 'timeout'" raise XMLSchemaTypeError(msg % type(timeout)) elif timeout <= 0: msg = "the argument 'timeout' must be a positive integer" raise XMLSchemaValueError(msg) self._timeout = timeout if not isinstance(thin_lazy, bool): msg = "invalid type %r for argument 'thin_lazy'" raise XMLSchemaTypeError(msg % type(thin_lazy)) self._thin_lazy = thin_lazy if uri_mapper is not None and not callable(uri_mapper) \ and not isinstance(uri_mapper, MutableMapping): msg = "invalid type %r for argument 'uri_mapper'" raise XMLSchemaTypeError(msg % type(uri_mapper)) self._uri_mapper = uri_mapper self.parse(source, lazy)
(self, source: Optional[~T], base_url: Union[NoneType, str, pathlib.Path, bytes] = None, allow: str = 'all', defuse: str = 'remote', timeout: int = 300, lazy: Union[bool, int] = False, thin_lazy: bool = True, uri_mapper: Optional[~T] = None) -> NoneType
713,316
xmlschema.resources
__repr__
null
def __repr__(self) -> str: return '%s(root=%r)' % (self.__class__.__name__, self._root)
(self) -> str
713,317
xmlschema.resources
_access_control
null
def _access_control(self, url: str) -> None: if self._allow == 'all': return elif self._allow == 'none': raise XMLResourceError(f"block access to resource {url}") elif self._allow == 'remote': if is_local_url(url): raise XMLResourceError(f"block access to local resource {url}") elif is_remote_url(url): raise XMLResourceError(f"block access to remote resource {url}") elif self._allow == 'sandbox' and self._base_url is not None: if not url.startswith(normalize_url(self._base_url)): raise XMLResourceError(f"block access to out of sandbox file {url}")
(self, url: str) -> NoneType
713,318
xmlschema.resources
_get_parsed_url
null
def _get_parsed_url(self, url: str) -> str: if isinstance(self._uri_mapper, MutableMapping): if url in self._uri_mapper: url = self._uri_mapper[url] elif callable(self._uri_mapper): url = self._uri_mapper(url) url = normalize_url(url, self._base_url) self._access_control(url) return url
(self, url: str) -> str
713,319
xmlschema.resources
_lazy_clear
null
def _lazy_clear(self, elem: ElementType, ancestors: Optional[List[ElementType]] = None) -> None: if ancestors and self._thin_lazy: # Delete preceding elements for parent, child in zip_longest(ancestors, ancestors[1:]): if child is None: child = elem for k, e in enumerate(parent): if child is not e: if e in self._xmlns: del self._xmlns[e] del self._nsmaps[e] else: if k: del parent[:k] break for e in elem.iter(): if elem is not e: if e in self._xmlns: del self._xmlns[e] del self._nsmaps[e] del elem[:] # delete children, keep attributes, text and tail. # reset the whole XPath tree to let it still usable if other # children are added to the root by ElementTree.iterparse(). self.xpath_root.children.clear()
(self, elem: Optional[~T], ancestors: Optional[List[Optional[~T]]] = None) -> NoneType
713,320
xmlschema.resources
_lazy_iterparse
null
def _lazy_iterparse(self, resource: IO[AnyStr]) -> Iterator[Tuple[str, ElementType]]: events: Tuple[str, ...] events = 'start-ns', 'end-ns', 'start', 'end' if self._defuse == 'remote' and is_remote_url(self.base_url) \ or self._defuse == 'nonlocal' and not is_local_url(self.base_url) \ or self._defuse == 'always': safe_parser = SafeXMLParser(target=PyElementTree.TreeBuilder()) tree_iterator = PyElementTree.iterparse(resource, events, safe_parser) else: tree_iterator = ElementTree.iterparse(resource, events) root_started = False start_ns: List[Tuple[str, str]] = [] end_ns = False nsmap_stack: List[Dict[str, str]] = [{}] # Save previous status (if any) _root: Optional[ElementType] _nsmaps: Optional[Dict[ElementType, Dict[str, str]]] _ns_declarations: Optional[Dict[ElementType, List[Tuple[str, str]]]] if hasattr(self, '_root'): _root = self._root _nsmaps = self._nsmaps _ns_declarations = self._xmlns _xpath_root = self._xpath_root else: _root = _nsmaps = _ns_declarations = _xpath_root = None self._nsmaps = {} self._xmlns = {} try: for event, node in tree_iterator: if event == 'start': if end_ns: nsmap_stack.pop() end_ns = False if start_ns: nsmap_stack.append(nsmap_stack[-1].copy()) nsmap_stack[-1].update(start_ns) self._xmlns[node] = start_ns start_ns = [] self._nsmaps[node] = nsmap_stack[-1] if not root_started: self._root = node self._xpath_root = LazyElementNode( self._root, nsmap=self._nsmaps[node] ) root_started = True yield event, node elif event == 'end': if end_ns: nsmap_stack.pop() end_ns = False yield event, node elif event == 'start-ns': start_ns.append(node) else: end_ns = True except Exception as err: if _root is not None \ and _nsmaps is not None \ and _ns_declarations is not None: self._root = _root self._nsmaps = _nsmaps self._xmlns = _ns_declarations self._xpath_root = _xpath_root if isinstance(err, PyElementTree.ParseError): raise ElementTree.ParseError(str(err)) from None raise
(self, resource: IO[~AnyStr]) -> Iterator[Tuple[str, Optional[~T]]]
713,321
xmlschema.resources
_parse
null
def _parse(self, resource: IO[AnyStr]) -> None: if self._defuse == 'remote' and is_remote_url(self.base_url) \ or self._defuse == 'nonlocal' and not is_local_url(self.base_url) \ or self._defuse == 'always': if not hasattr(resource, 'seekable') or not resource.seekable(): text = resource.read() if isinstance(text, str): resource = StringIO(text) else: resource = BytesIO(text) safe_parser = SafeXMLParser(target=PyElementTree.TreeBuilder()) try: for _ in PyElementTree.iterparse(resource, ('start',), safe_parser): break except PyElementTree.ParseError as err: raise ElementTree.ParseError(str(err)) else: resource.seek(0) root: Optional[ElementType] = None start_ns: List[Tuple[str, str]] = [] end_ns = False nsmaps: Dict[ElementType, Dict[str, str]] = {} ns_declarations: Dict[ElementType, List[Tuple[str, str]]] = {} events = 'start-ns', 'end-ns', 'start' nsmap_stack: List[Dict[str, str]] = [{}] for event, node in ElementTree.iterparse(resource, events): if event == 'start': if root is None: root = node if end_ns: nsmap_stack.pop() end_ns = False if start_ns: nsmap_stack.append(nsmap_stack[-1].copy()) nsmap_stack[-1].update(start_ns) ns_declarations[node] = start_ns start_ns = [] nsmaps[node] = nsmap_stack[-1] elif event == 'start-ns': start_ns.append(node) else: end_ns = True assert root is not None self._root = root self._xpath_root = None self._nsmaps = nsmaps self._xmlns = ns_declarations
(self, resource: IO[~AnyStr]) -> NoneType
713,322
xmlschema.resources
_parse_resource
null
def _parse_resource(self, resource: IO[AnyStr], url: Optional[str], lazy: Union[bool, int]) -> None: _url, self._url = self._url, url try: if not lazy: self._parse(resource) else: for _, root in self._lazy_iterparse(resource): # pragma: no cover break except Exception: self._url = _url raise
(self, resource: IO[~AnyStr], url: Optional[str], lazy: Union[bool, int]) -> NoneType
713,323
xmlschema.resources
_select_elements
null
def _select_elements(self, token: XPathToken, node: ResourceNodeType, ancestors: Optional[List[ElementType]] = None) -> Iterator[ElementType]: context = XPathContext(node) for item in token.select(context): if not isinstance(item, ElementNode): # pragma: no cover msg = "XPath expressions on XML resources can select only elements" raise XMLResourceError(msg) elif ancestors is not None: if item.elem is self._root: ancestors.clear() else: _ancestors: Any = [] parent = item.parent while parent is not None: _ancestors.append(parent.value) parent = parent.parent if _ancestors: ancestors.clear() ancestors.extend(reversed(_ancestors)) yield cast(ElementType, item.elem)
(self, token: elementpath.xpath_tokens.XPathToken, node: Union[elementpath.xpath_nodes.ElementNode, elementpath.xpath_nodes.LazyElementNode, elementpath.xpath_nodes.DocumentNode], ancestors: Optional[List[Optional[~T]]] = None) -> Iterator[Optional[~T]]
713,324
xmlschema.resources
close
Close the XML resource if it's created with a file-like object. In other cases this method has no effect.
def close(self) -> None: """ Close the XML resource if it's created with a file-like object. In other cases this method has no effect. """ try: self._source.close() # type: ignore[union-attr] except (AttributeError, TypeError): pass
(self) -> NoneType
713,325
xmlschema.resources
find
null
def find(self, path: str, namespaces: Optional[NamespacesType] = None, ancestors: Optional[List[ElementType]] = None) -> Optional[ElementType]: return next(self.iterfind(path, namespaces, ancestors), None)
(self, path: str, namespaces: Optional[~T] = None, ancestors: Optional[List[Optional[~T]]] = None) -> Optional[~T]
713,326
xmlschema.resources
findall
null
def findall(self, path: str, namespaces: Optional[NamespacesType] = None) \ -> List[ElementType]: return list(self.iterfind(path, namespaces))
(self, path: str, namespaces: Optional[~T] = None) -> List[Optional[~T]]
713,327
xmlschema.resources
get_absolute_path
null
def get_absolute_path(self, path: Optional[str] = None) -> str: if path is None: if self._lazy: return f"/{self._root.tag}/{'/'.join('*' * int(self._lazy))}" return f'/{self._root.tag}' elif path.startswith('/'): return path else: return f'/{self._root.tag}/{path}'
(self, path: Optional[str] = None) -> str
713,328
xmlschema.resources
get_locations
Extracts a list of schema location hints from the XML resource. The locations are normalized using the base URL of the instance. :param locations: a sequence of schema location hints inserted before the ones extracted from the XML resource. Locations passed within a tuple container are not normalized. :param root_only: if `True` extracts only the location hints of the root element. :returns: a list of couples containing normalized location hints.
def get_locations(self, locations: Optional[LocationsType] = None, root_only: bool = True) -> NormalizedLocationsType: """ Extracts a list of schema location hints from the XML resource. The locations are normalized using the base URL of the instance. :param locations: a sequence of schema location hints inserted \ before the ones extracted from the XML resource. Locations passed \ within a tuple container are not normalized. :param root_only: if `True` extracts only the location hints of the \ root element. :returns: a list of couples containing normalized location hints. """ if not locations: location_hints = [] elif isinstance(locations, tuple): location_hints = [x for x in locations] else: location_hints = normalize_locations(locations, self.base_url) if root_only: location_hints.extend([ (ns, normalize_url(url, self.base_url)) for ns, url in etree_iter_location_hints(self._root) ]) else: try: location_hints.extend([ (ns, normalize_url(url, self.base_url)) for ns, url in self.iter_location_hints() ]) except (ElementTree.ParseError, PyElementTree.ParseError, UnicodeEncodeError): pass # a lazy resource containing malformed XML data after the first tag return location_hints
(self, locations: Optional[~T] = None, root_only: bool = True) -> Optional[~T]
713,329
xmlschema.resources
get_namespaces
Extracts namespaces with related prefixes from the XML resource. If a duplicate prefix is encountered in a xmlns declaration, and this is mapped to a different namespace, adds the namespace using a different generated prefix. The empty prefix '' is used only if it's declared at root level to avoid erroneous mapping of local names. In other cases it uses the prefix 'default' as substitute. :param namespaces: is an optional mapping from namespace prefix to URI that integrate/override the namespace declarations of the root element. :param root_only: if `True` extracts only the namespaces declared in the root element, otherwise scan the whole tree for further namespace declarations. A full namespace map can be useful for cases where the element context is not available. :return: a dictionary for mapping namespace prefixes to full URI.
def get_namespaces(self, namespaces: Optional[NamespacesType] = None, root_only: bool = True) -> NamespacesType: """ Extracts namespaces with related prefixes from the XML resource. If a duplicate prefix is encountered in a xmlns declaration, and this is mapped to a different namespace, adds the namespace using a different generated prefix. The empty prefix '' is used only if it's declared at root level to avoid erroneous mapping of local names. In other cases it uses the prefix 'default' as substitute. :param namespaces: is an optional mapping from namespace prefix to URI that \ integrate/override the namespace declarations of the root element. :param root_only: if `True` extracts only the namespaces declared in the root \ element, otherwise scan the whole tree for further namespace declarations. \ A full namespace map can be useful for cases where the element context is \ not available. :return: a dictionary for mapping namespace prefixes to full URI. """ namespaces = get_namespace_map(namespaces) try: for elem in self.iter(): if elem in self._xmlns: update_namespaces(namespaces, self._xmlns[elem], elem is self._root) if root_only: break except (ElementTree.ParseError, PyElementTree.ParseError, UnicodeEncodeError): return namespaces # a lazy resource with malformed XML data else: return namespaces
(self, namespaces: Optional[~T] = None, root_only: bool = True) -> Optional[~T]
713,330
xmlschema.resources
get_nsmap
Returns the namespace map (nsmap) of the element. Returns `None` if no nsmap is found for the element. Lazy resources have only the nsmap for the root element.
def get_nsmap(self, elem: ElementType) -> Optional[Dict[str, str]]: """ Returns the namespace map (nsmap) of the element. Returns `None` if no nsmap is found for the element. Lazy resources have only the nsmap for the root element. """ try: return self._nsmaps[elem] except KeyError: return getattr(elem, 'nsmap', None) # an lxml element
(self, elem: Optional[~T]) -> Optional[Dict[str, str]]
713,331
xmlschema.resources
get_text
Gets the source text of the XML document. If the source text is not available creates an encoded string representation of the XML tree. Il the resource is lazy raises a resource error.
def get_text(self) -> str: """ Gets the source text of the XML document. If the source text is not available creates an encoded string representation of the XML tree. Il the resource is lazy raises a resource error. """ if self._text is not None: return self._text elif self._url is not None: self.load() if self._text is not None: return self._text return self.tostring(xml_declaration=True)
(self) -> str
713,332
xmlschema.resources
get_xmlns
Returns the list of namespaces declarations (xmlns and xmlns:<prefix> attributes) of the element. Returns `None` if the element doesn't have namespace declarations. Lazy resources have only the namespace declarations for the root element.
def get_xmlns(self, elem: ElementType) -> Optional[List[Tuple[str, str]]]: """ Returns the list of namespaces declarations (xmlns and xmlns:<prefix> attributes) of the element. Returns `None` if the element doesn't have namespace declarations. Lazy resources have only the namespace declarations for the root element. """ return self._xmlns.get(elem)
(self, elem: Optional[~T]) -> Optional[List[Tuple[str, str]]]
713,333
xmlschema.resources
get_xpath_node
Returns an XPath node for the element, fetching it from the XPath root node. Returns a new lazy element node if the matching element node is not found.
def get_xpath_node(self, elem: ElementType) -> ElementNode: """ Returns an XPath node for the element, fetching it from the XPath root node. Returns a new lazy element node if the matching element node is not found. """ xpath_node = self.xpath_root.get_element_node(elem) if xpath_node is not None: return xpath_node try: return LazyElementNode(elem, nsmap=self._nsmaps[elem]) except KeyError: return LazyElementNode(elem)
(self, elem: Optional[~T]) -> elementpath.xpath_nodes.ElementNode
713,334
xmlschema.resources
is_lazy
Returns `True` if the XML resource is lazy.
def is_lazy(self) -> bool: """Returns `True` if the XML resource is lazy.""" return bool(self._lazy)
(self) -> bool
713,335
xmlschema.resources
is_loaded
Returns `True` if the XML text of the data source is loaded.
def is_loaded(self) -> bool: """Returns `True` if the XML text of the data source is loaded.""" return self._text is not None
(self) -> bool
713,336
xmlschema.resources
is_local
Returns `True` if the resource is related with local XML data.
def is_local(self) -> bool: """Returns `True` if the resource is related with local XML data.""" return is_local_url(self._url)
(self) -> bool
713,337
xmlschema.resources
is_remote
Returns `True` if the resource is related with remote XML data.
def is_remote(self) -> bool: """Returns `True` if the resource is related with remote XML data.""" return is_remote_url(self._url)
(self) -> bool
713,338
xmlschema.resources
is_thin
Returns `True` if the XML resource is lazy and thin.
def is_thin(self) -> bool: """Returns `True` if the XML resource is lazy and thin.""" return bool(self._lazy) and self._thin_lazy
(self) -> bool
713,339
xmlschema.resources
iter
XML resource tree iterator. If tag is not None or '*', only elements whose tag equals tag are returned from the iterator. In a lazy resource the yielded elements are full over or at *lazy_depth* level, otherwise are incomplete and thin for default.
def iter(self, tag: Optional[str] = None) -> Iterator[ElementType]: """ XML resource tree iterator. If tag is not None or '*', only elements whose tag equals tag are returned from the iterator. In a lazy resource the yielded elements are full over or at *lazy_depth* level, otherwise are incomplete and thin for default. """ if not self._lazy: yield from self._root.iter(tag) return resource = self.open() tag = '*' if tag is None else tag.strip() lazy_depth = int(self._lazy) subtree_elements: Deque[ElementType] = deque() ancestors = [] level = 0 try: for event, node in self._lazy_iterparse(resource): if event == "start": if level < lazy_depth: if level: ancestors.append(node) if tag == '*' or node.tag == tag: yield node # an incomplete element level += 1 else: level -= 1 if level < lazy_depth: if level: ancestors.pop() continue # pragma: no cover elif level > lazy_depth: if tag == '*' or node.tag == tag: subtree_elements.appendleft(node) continue # pragma: no cover if tag == '*' or node.tag == tag: yield node # a full element yield from subtree_elements subtree_elements.clear() self._lazy_clear(node, ancestors) finally: # Close the resource only if it was originally opened by XMLResource if resource is not self._source: resource.close()
(self, tag: Optional[str] = None) -> Iterator[Optional[~T]]
713,340
xmlschema.resources
iter_depth
Iterates XML subtrees. For fully loaded resources yields the root element. On lazy resources the argument *mode* can change the sequence and the completeness of yielded elements. There are four possible modes, that generate different sequences of elements: 1. Only the elements at *depth_level* level of the tree 2. Only the elements at *depth_level* level of the tree removing the preceding elements of ancestors (thin lazy tree) 3. Only a root element pruned at *depth_level* 4. The elements at *depth_level* and then a pruned root 5. An incomplete root at start, the elements at *depth_level* and a pruned root :param mode: an integer in range [1..5] that defines the iteration mode. :param ancestors: provide a list for tracking the ancestors of yielded elements.
def iter_depth(self, mode: int = 1, ancestors: Optional[List[ElementType]] = None) \ -> Iterator[ElementType]: """ Iterates XML subtrees. For fully loaded resources yields the root element. On lazy resources the argument *mode* can change the sequence and the completeness of yielded elements. There are four possible modes, that generate different sequences of elements:\n 1. Only the elements at *depth_level* level of the tree\n 2. Only the elements at *depth_level* level of the tree removing\n the preceding elements of ancestors (thin lazy tree) 3. Only a root element pruned at *depth_level*\n 4. The elements at *depth_level* and then a pruned root\n 5. An incomplete root at start, the elements at *depth_level* and a pruned root\n :param mode: an integer in range [1..5] that defines the iteration mode. :param ancestors: provide a list for tracking the ancestors of yielded elements. """ if mode not in (1, 2, 3, 4, 5): raise XMLSchemaValueError(f"invalid argument mode={mode!r}") if ancestors is not None: ancestors.clear() elif mode <= 2: ancestors = [] if not self._lazy: yield self._root return resource = self.open() level = 0 lazy_depth = int(self._lazy) # boolean flags incomplete_root = mode == 5 pruned_root = mode > 2 depth_level_elements = mode != 3 thin_lazy = mode <= 2 try: for event, elem in self._lazy_iterparse(resource): if event == "start": if not level: if incomplete_root: yield elem if ancestors is not None and level < lazy_depth: ancestors.append(elem) level += 1 else: level -= 1 if not level: if pruned_root: yield elem continue elif level != lazy_depth: if ancestors is not None and level < lazy_depth: ancestors.pop() continue # pragma: no cover elif depth_level_elements: yield elem if thin_lazy: self._lazy_clear(elem, ancestors) else: self._lazy_clear(elem) finally: if self._source is not resource: resource.close()
(self, mode: int = 1, ancestors: Optional[List[Optional[~T]]] = None) -> Iterator[Optional[~T]]
713,341
xmlschema.resources
iter_location_hints
Yields all schema location hints of the XML resource. If tag is not None or '*', only location hints of elements whose tag equals tag are returned from the iterator.
def iter_location_hints(self, tag: Optional[str] = None) -> Iterator[Tuple[str, str]]: """ Yields all schema location hints of the XML resource. If tag is not None or '*', only location hints of elements whose tag equals tag are returned from the iterator. """ for elem in self.iter(tag): yield from etree_iter_location_hints(elem)
(self, tag: Optional[str] = None) -> Iterator[Tuple[str, str]]
713,342
xmlschema.resources
iterfind
Apply XPath selection to XML resource that yields full subtrees. :param path: an XPath 2.0 expression that selects element nodes. Selecting other values or nodes raise an error. :param namespaces: an optional mapping from namespace prefixes to URIs used for parsing the XPath expression. :param ancestors: provide a list for tracking the ancestors of yielded elements.
def iterfind(self, path: str, namespaces: Optional[NamespacesType] = None, ancestors: Optional[List[ElementType]] = None) -> Iterator[ElementType]: """ Apply XPath selection to XML resource that yields full subtrees. :param path: an XPath 2.0 expression that selects element nodes. \ Selecting other values or nodes raise an error. :param namespaces: an optional mapping from namespace prefixes to URIs \ used for parsing the XPath expression. :param ancestors: provide a list for tracking the ancestors of yielded elements. """ parser = XPath2Parser(namespaces, strict=False) token = parser.parse(path) if not self._lazy: yield from self._select_elements(token, self.xpath_root, ancestors) return resource = self.open() lazy_depth = int(self._lazy) level = 0 path = path.replace(' ', '').replace('./', '') select_all = '*' in path and set(path).issubset(('*', '/')) if path == '.': path_depth = 0 elif path.startswith('/'): path_depth = path.count('/') - 1 else: path_depth = path.count('/') + 1 if not path_depth: raise XMLResourceError(f"cannot use path {path!r} on a lazy resource") elif path_depth < lazy_depth: raise XMLResourceError(f"cannot use path {path!r} on a lazy resource " f"with lazy_depth=={lazy_depth}") if ancestors is not None: ancestors.clear() elif self._thin_lazy: ancestors = [] try: for event, node in self._lazy_iterparse(resource): if event == "start": if ancestors is not None and level < path_depth: ancestors.append(node) level += 1 else: level -= 1 if level < path_depth: if ancestors is not None: ancestors.pop() continue elif level == path_depth: if select_all or \ node in self._select_elements(token, self.xpath_root): yield node if level == lazy_depth: self._lazy_clear(node, ancestors) finally: if self._source is not resource: resource.close()
(self, path: str, namespaces: Optional[~T] = None, ancestors: Optional[List[Optional[~T]]] = None) -> Iterator[Optional[~T]]
713,343
xmlschema.resources
load
Loads the XML text from the data source. If the data source is an Element the source XML text can't be retrieved.
def load(self) -> None: """ Loads the XML text from the data source. If the data source is an Element the source XML text can't be retrieved. """ if self._url is None and not hasattr(self._source, 'read'): return # Created from Element or text source --> already loaded elif self._lazy: raise XMLResourceError("cannot load a lazy XML resource") resource = self.open() try: data = resource.read() finally: # We don't want to close the file obj if it wasn't originally # opened by `XMLResource`. That is the concern of the code # where the file obj came from. if resource is not self._source: resource.close() if isinstance(data, bytes): try: text = data.decode('utf-8') except UnicodeDecodeError: text = data.decode('iso-8859-1') else: text = data self._text = text
(self) -> NoneType
713,344
xmlschema.resources
open
Returns an opened resource reader object for the instance URL. If the source attribute is a seekable file-like object rewind the source and return it.
def open(self) -> IO[AnyStr]: """ Returns an opened resource reader object for the instance URL. If the source attribute is a seekable file-like object rewind the source and return it. """ if self.seek(0) == 0: return cast(IO[AnyStr], self._source) elif self._url is None: raise XMLResourceError(f"can't open, {self!r} has no URL associated") try: return cast(IO[AnyStr], urlopen(self._url, timeout=self._timeout)) except URLError as err: msg = "cannot access to resource %(url)r: %(reason)s" raise XMLResourceError(msg % {'url': self._url, 'reason': err.reason})
(self) -> IO[~AnyStr]
713,345
xmlschema.resources
parse
null
def parse(self, source: XMLSourceType, lazy: Union[bool, int] = False) -> None: if isinstance(lazy, bool): pass elif not isinstance(lazy, int): msg = "invalid type %r for the attribute 'lazy'" raise XMLSchemaTypeError(msg % type(lazy)) elif lazy < 0: msg = "invalid value %r for the attribute 'lazy'" raise XMLSchemaValueError(msg % lazy) url: Optional[str] if isinstance(source, str): if is_url(source): # source is a string containing a URL or a file path url = self._get_parsed_url(source.strip()) with urlopen(url, timeout=self._timeout) as resource: self._parse_resource(resource, url, lazy) self._text = None self._lazy = lazy else: # source is a string containing an XML document resource = StringIO(source) self._parse_resource(resource, None, lazy) self._text = source self._lazy = False elif isinstance(source, bytes): if is_url(source): # source is a byte-string containing a URL or a file path url = self._get_parsed_url(source.decode().strip()) with urlopen(url, timeout=self._timeout) as resource: self._parse_resource(resource, url, lazy) self._text = None self._lazy = lazy else: resource = BytesIO(source) self._parse_resource(resource, None, lazy) self._text = source.decode() self._lazy = False elif isinstance(source, Path): url = self._get_parsed_url(str(source)) with urlopen(url, timeout=self._timeout) as resource: self._parse_resource(resource, url, lazy) self._text = None self._lazy = lazy elif isinstance(source, StringIO): self._parse_resource(source, None, lazy) self._text = source.getvalue() self._lazy = lazy elif hasattr(source, 'read'): # source is a readable resource (remote or local file) url = getattr(source, 'url', None) if url is not None: self._access_control(url) # Save remote urls for open new resources (non seekable) if not is_remote_url(url): url = None self._parse_resource(cast(IO[str], source), url, lazy) self._text = None self._lazy = lazy else: # source is an Element or an ElementTree if hasattr(source, 'tag') and hasattr(source, 'attrib'): # Source is already an Element --> nothing to parse self._root = cast(ElementType, source) elif is_etree_document(source): # Could be only an ElementTree object at last self._root = source.getroot() else: raise XMLSchemaTypeError( "wrong type %r for 'source' attribute: an ElementTree object or " "an Element instance or a string containing XML data or an URL " "or a file-like object is required." % type(source) ) self._xpath_root = None self._text = self._url = None self._lazy = False self._nsmaps = {} self._xmlns = {} if hasattr(self._root, 'xpath'): nsmap = {} lxml_nsmap = None for elem in cast(Any, self._root.iter()): if callable(elem.tag): self._nsmaps[elem] = {} continue if lxml_nsmap != elem.nsmap: nsmap = {k or '': v for k, v in elem.nsmap.items()} lxml_nsmap = elem.nsmap parent = elem.getparent() if parent is None: ns_declarations = [(k or '', v) for k, v in nsmap.items()] elif parent.nsmap != elem.nsmap: ns_declarations = [(k or '', v) for k, v in elem.nsmap.items() if k not in parent.nsmap or v != parent.nsmap[k]] else: ns_declarations = None self._nsmaps[elem] = nsmap if ns_declarations: self._xmlns[elem] = ns_declarations self._parent_map = None self._source = source
(self, source: Optional[~T], lazy: Union[bool, int] = False) -> NoneType
713,346
xmlschema.resources
seek
Change stream position if the XML resource was created with a seekable file-like object. In the other cases this method has no effect.
def seek(self, position: int) -> Optional[int]: """ Change stream position if the XML resource was created with a seekable file-like object. In the other cases this method has no effect. """ if not hasattr(self._source, 'read'): return None try: if not self._source.seekable(): # type: ignore[union-attr] return None except AttributeError: return None # pragma: no cover except ValueError as err: raise XMLResourceError(str(err)) from None else: return self._source.seek(position) # type: ignore[union-attr]
(self, position: int) -> Optional[int]
713,347
xmlschema.resources
subresource
Create an XMLResource instance from a subelement of a non-lazy XML tree.
def subresource(self, elem: ElementType) -> 'XMLResource': """Create an XMLResource instance from a subelement of a non-lazy XML tree.""" if self._lazy: raise XMLResourceError("cannot create a subresource from a lazy XML resource") for e in self._root.iter(): # pragma: no cover if e is elem: break else: msg = "{!r} is not an element or the XML resource tree" raise XMLResourceError(msg.format(elem)) resource = XMLResource(elem, self.base_url, self._allow, self._defuse, self._timeout) if not hasattr(elem, 'nsmap'): for e in elem.iter(): resource._nsmaps[e] = self._nsmaps[e] if e is elem: ns_declarations = [(k, v) for k, v in self._nsmaps[e].items()] if ns_declarations: resource._xmlns[e] = ns_declarations elif e in self._xmlns: resource._xmlns[e] = self._xmlns[e] return resource
(self, elem: Optional[~T]) -> xmlschema.resources.XMLResource
713,348
xmlschema.resources
tostring
Serialize an XML resource to a string. :param namespaces: is an optional mapping from namespace prefix to URI. Provided namespaces are registered before serialization. Ignored if the provided *elem* argument is a lxml Element instance. :param indent: the baseline indentation. :param max_lines: if truncate serialization after a number of lines (default: do not truncate). :param spaces_for_tab: number of spaces for replacing tab characters. For default tabs are replaced with 4 spaces, provide `None` to keep tab characters. :param xml_declaration: if set to `True` inserts the XML declaration at the head. :param encoding: if "unicode" (the default) the output is a string, otherwise it’s binary. :param method: is either "xml" (the default), "html" or "text". :return: a Unicode string.
def tostring(self, namespaces: Optional[MutableMapping[str, str]] = None, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: int = 4, xml_declaration: bool = False, encoding: str = 'unicode', method: str = 'xml') -> str: """ Serialize an XML resource to a string. :param namespaces: is an optional mapping from namespace prefix to URI. \ Provided namespaces are registered before serialization. Ignored if the \ provided *elem* argument is a lxml Element instance. :param indent: the baseline indentation. :param max_lines: if truncate serialization after a number of lines \ (default: do not truncate). :param spaces_for_tab: number of spaces for replacing tab characters. For \ default tabs are replaced with 4 spaces, provide `None` to keep tab characters. :param xml_declaration: if set to `True` inserts the XML declaration at the head. :param encoding: if "unicode" (the default) the output is a string, \ otherwise it’s binary. :param method: is either "xml" (the default), "html" or "text". :return: a Unicode string. """ if self._lazy: raise XMLResourceError("cannot serialize a lazy XML resource") if not hasattr(self._root, 'nsmap'): namespaces = self.get_namespaces(namespaces, root_only=False) _string = etree_tostring( elem=self._root, namespaces=namespaces, indent=indent, max_lines=max_lines, spaces_for_tab=spaces_for_tab, xml_declaration=xml_declaration, encoding=encoding, method=method ) if isinstance(_string, bytes): # pragma: no cover return _string.decode('utf-8') return _string
(self, namespaces: Optional[MutableMapping[str, str]] = None, indent: str = '', max_lines: Optional[int] = None, spaces_for_tab: int = 4, xml_declaration: bool = False, encoding: str = 'unicode', method: str = 'xml') -> str
713,349
xmlschema.exceptions
XMLResourceError
Raised when an error is found accessing an XML resource.
class XMLResourceError(XMLSchemaException, OSError): """Raised when an error is found accessing an XML resource."""
null
713,350
xmlschema.validators.schemas
XMLSchema10
XSD 1.0 schema class. <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 XMLSchema10(XMLSchemaBase): """ XSD 1.0 schema class. <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.0/XMLSchema.xsd') # type: ignore 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'), }
(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,352
xmlschema.validators.schemas
copy
Makes a copy of the schema instance. The new instance has independent maps of shared XSD components.
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
(self) -> Optional[~T]
713,354
xmlschema.validators.schemas
__getstate__
null
def __getstate__(self) -> Dict[str, Any]: state = self.__dict__.copy() state.pop('lock', None) state.pop('xpath_tokens', None) return state
(self) -> Dict[str, Any]
713,355
xmlschema.validators.schemas
__init__
null
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
(self, source: Union[~T, NoneType, List[Optional[~T]]], namespace: Optional[str] = None, validation: str = 'strict', global_maps: Optional[xmlschema.validators.global_maps.XsdGlobals] = None, converter: Optional[~T] = None, locations: Optional[~T] = 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) -> NoneType
713,356
xmlschema.validators.schemas
__iter__
null
def __iter__(self) -> Iterator[XsdElement]: yield from sorted(self.elements.values(), key=name_attribute)
(self) -> Iterator[xmlschema.validators.elements.XsdElement]
713,358
xmlschema.validators.schemas
__repr__
null
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)
(self) -> str
713,359
xmlschema.validators.schemas
__reversed__
null
def __reversed__(self) -> Iterator[XsdElement]: yield from sorted(self.elements.values(), key=name_attribute, reverse=True)
(self) -> Iterator[xmlschema.validators.elements.XsdElement]
713,360
xmlschema.validators.schemas
__setattr__
null
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)
(self, name: str, value: Any) -> NoneType
713,361
xmlschema.validators.schemas
__setstate__
null
def __setstate__(self, state: Dict[str, Any]) -> None: self.__dict__.update(state) self.lock = threading.Lock()
(self, state: Dict[str, Any]) -> NoneType
713,363
xmlschema.validators.schemas
_import_namespace
null
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
(self, namespace: str, locations: List[str]) -> NoneType
713,364
xmlschema.validators.schemas
_parse_imports
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.
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)
(self) -> NoneType
713,365
xmlschema.validators.schemas
_parse_inclusions
Processes schema document inclusions and redefinitions/overrides.
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
(self) -> NoneType
713,366
xmlschema.validators.xsdbase
_parse_xpath_default_namespace
Parse XSD 1.1 xpathDefaultNamespace attribute for schema, alternative, assert, assertion and selector declarations, checking if the value is conforming to the specification. In case the attribute is missing or for wrong attribute values defaults to ''.
def _parse_xpath_default_namespace(self, elem: ElementType) -> str: """ Parse XSD 1.1 xpathDefaultNamespace attribute for schema, alternative, assert, assertion and selector declarations, checking if the value is conforming to the specification. In case the attribute is missing or for wrong attribute values defaults to ''. """ try: value = elem.attrib['xpathDefaultNamespace'] except KeyError: return '' value = value.strip() if value == '##local': return '' elif value == '##defaultNamespace': default_namespace = getattr(self, 'default_namespace', None) return default_namespace if isinstance(default_namespace, str) else '' elif value == '##targetNamespace': target_namespace = getattr(self, 'target_namespace', '') return target_namespace if isinstance(target_namespace, str) else '' elif len(value.split()) == 1: return value else: admitted_values = ('##defaultNamespace', '##targetNamespace', '##local') msg = _("wrong value {0!r} for 'xpathDefaultNamespace' " "attribute, can be (anyURI | {1}).") self.parse_error(msg.format(value, ' | '.join(admitted_values)), elem) return ''
(self, elem: Optional[~T]) -> str
713,367
xmlschema.validators.schemas
_validate_references
null
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)
(self, source: xmlschema.resources.XMLResource, validation: str = 'lax', id_map: Optional[Counter[str]] = None, identities: Optional[Dict[Union[xmlschema.validators.identities.XsdKey, xmlschema.validators.identities.XsdKeyref, str, NoneType], Union[xmlschema.validators.identities.IdentityCounter, xmlschema.validators.identities.KeyrefCounter]]] = None, **kwargs: Any) -> Iterator[xmlschema.validators.exceptions.XMLSchemaValidationError]
713,368
xmlschema.validators.schemas
add_schema
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.
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, )
(self, source: Optional[~T], namespace: Optional[str] = None, build: bool = False) -> Optional[~T]
713,369
xmlschema.validators.schemas
build
Builds the schema's XSD global maps.
def build(self) -> None: """Builds the schema's XSD global maps.""" self.maps.build()
(self) -> NoneType
713,370
xmlschema.validators.schemas
check_validator
Checks the status of a schema validator against a validation mode.
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)
(self, validation: str = 'strict') -> NoneType
713,371
xmlschema.validators.schemas
clear
Clears the schema's XSD global maps.
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
(self) -> NoneType
713,374
xmlschema.validators.schemas
create_any_attribute_group
Creates an attribute group related to schema instance that accepts any attribute. :param parent: the parent component to set for the attribute group.
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
(self, parent: Union[xmlschema.validators.complex_types.XsdComplexType, xmlschema.validators.elements.XsdElement]) -> xmlschema.validators.attributes.XsdAttributeGroup
713,375
xmlschema.validators.schemas
create_any_content_group
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'.
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
(self, parent: Union[xmlschema.validators.complex_types.XsdComplexType, xmlschema.validators.groups.XsdGroup], any_element: Optional[xmlschema.validators.wildcards.XsdAnyElement] = None) -> xmlschema.validators.groups.XsdGroup
713,376
xmlschema.validators.schemas
create_any_type
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.
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
(self) -> xmlschema.validators.complex_types.XsdComplexType
713,377
xmlschema.validators.schemas
create_bindings
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.
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)
(self, *bases: type, **attrs: Any) -> NoneType
713,378
xmlschema.validators.schemas
create_element
Creates a xs:element instance related to schema component. Used as dummy element for validation/decoding/encoding operations of wildcards and complex types.
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)
(self, name: str, parent: Optional[xmlschema.validators.xsdbase.XsdComponent] = None, text: Optional[str] = None, **attrib: Any) -> xmlschema.validators.elements.XsdElement
713,379
xmlschema.validators.schemas
create_empty_attribute_group
Creates an empty attribute group related to schema instance. :param parent: the parent component to set for the 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)
(self, parent: Union[xmlschema.validators.complex_types.XsdComplexType, xmlschema.validators.elements.XsdElement]) -> xmlschema.validators.attributes.XsdAttributeGroup
713,380
xmlschema.validators.schemas
create_empty_content_group
null
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)
(self, parent: Union[xmlschema.validators.complex_types.XsdComplexType, xmlschema.validators.groups.XsdGroup], model: str = 'sequence', **attrib: Any) -> xmlschema.validators.groups.XsdGroup
713,381
xmlschema.validators.schemas
decode
Decodes XML data. Takes the same arguments of the method :meth:`iter_decode`.
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
(self, source: Union[~T, NoneType, xmlschema.resources.XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, validation: str = 'strict', *args: Any, **kwargs: Any) -> Optional[Any]
713,382
xmlschema.validators.schemas
encode
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.
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
(self, obj: Any, path: Optional[str] = None, validation: str = 'strict', *args: Any, **kwargs: Any) -> Optional[Any]
713,383
xmlschema.validators.schemas
export
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.
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 )
(self, target: Union[str, pathlib.Path], save_remote: bool = False, remove_residuals: bool = True, exclude_locations: Optional[List[str]] = None, loglevel: Union[str, int, NoneType] = None) -> Dict[str, str]
713,387
xmlschema.validators.schemas
get_converter
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.
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))
(self, converter: Optional[~T] = None, **kwargs: Any) -> xmlschema.converters.default.XMLSchemaConverter
713,388
xmlschema.validators.schemas
get_element
null
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
(self, tag: str, path: Optional[str] = None, namespaces: Optional[~T] = None) -> Optional[xmlschema.validators.elements.XsdElement]
713,389
xmlschema.validators.schemas
get_locations
Get a list of location hints for a namespace.
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 []
(self, namespace: str) -> List[str]
713,390
xmlschema.validators.schemas
get_schema
Returns the first schema loaded for a namespace. Raises a `KeyError` if the requested namespace is not loaded.
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
(self, namespace: str) -> Optional[~T]
713,391
xmlschema.validators.schemas
get_text
Returns the source text of the XSD schema.
def get_text(self) -> str: """Returns the source text of the XSD schema.""" return self.source.get_text()
(self) -> str
713,392
xmlschema.validators.schemas
import_schema
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.
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
(self, namespace: str, location: str, base_url: Optional[str] = None, force: bool = False, build: bool = False) -> Optional[~T]
713,393
xmlschema.validators.schemas
include_schema
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.
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
(self, location: str, base_url: Optional[str] = None, build: bool = False) -> Optional[~T]
713,396
xmlschema.validators.schemas
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, 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
(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) -> bool
713,398
xmlschema.validators.schemas
iter_components
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.
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)
(self, xsd_classes: Optional[~T] = None) -> Iterator[Union[xmlschema.validators.xsdbase.XsdComponent, ~T, NoneType]]
713,399
xmlschema.validators.schemas
iter_decode
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.
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)
(self, source: Union[~T, NoneType, xmlschema.resources.XMLResource], path: Optional[str] = None, schema_path: Optional[str] = None, validation: str = 'lax', process_namespaces: bool = True, namespaces: Optional[~T] = 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[~T] = None, filler: Optional[~T] = 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[~T] = None, extra_validator: Optional[~T] = None, validation_hook: Optional[~T] = None, value_hook: Optional[~T] = None, element_hook: Optional[~T] = None, errors: Optional[List[xmlschema.validators.exceptions.XMLSchemaValidationError]] = None, **kwargs: Any) -> Iterator[Union[Any, xmlschema.validators.exceptions.XMLSchemaValidationError]]
713,400
xmlschema.validators.schemas
iter_encode
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.
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)
(self, obj: Any, path: Optional[str] = None, validation: str = 'lax', namespaces: Optional[~T] = None, use_defaults: bool = True, converter: Optional[~T] = None, unordered: bool = False, process_skipped: bool = False, max_depth: Optional[int] = None, **kwargs: Any) -> Iterator[Union[~T, NoneType, xmlschema.validators.exceptions.XMLSchemaValidationError]]
713,401
xmlschema.validators.schemas
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, 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)
(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, validation: str = 'lax') -> Iterator[xmlschema.validators.exceptions.XMLSchemaValidationError]
713,402
xmlschema.validators.schemas
iter_globals
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.
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())
(self, schema: Optional[~T] = None) -> Iterator[Union[~T, NoneType, Tuple[Any, ...]]]
713,405
xmlschema.validators.xsdbase
parse_error
Helper method for registering parse errors. Does nothing if validation mode is 'skip'. Il validation mode is 'lax' collects the error, otherwise raise the error. :param error: can be a parse error or an error message. :param elem: the Element instance related to the error, for default uses the 'elem' attribute of the validator, if it's present. :param validation: overrides the default validation mode of the validator.
def parse_error(self, error: Union[str, Exception], elem: Optional[ElementType] = None, validation: Optional[str] = None) -> None: """ Helper method for registering parse errors. Does nothing if validation mode is 'skip'. Il validation mode is 'lax' collects the error, otherwise raise the error. :param error: can be a parse error or an error message. :param elem: the Element instance related to the error, for default uses the 'elem' \ attribute of the validator, if it's present. :param validation: overrides the default validation mode of the validator. """ if validation is not None: check_validation_mode(validation) else: validation = self.validation if validation == 'skip': return elif elem is None: elem = self.elem elif not is_etree_element(elem): msg = "the argument 'elem' must be an Element instance, not {!r}." raise XMLSchemaTypeError(msg.format(elem)) if isinstance(error, XMLSchemaParseError): if error.namespaces is None: error.namespaces = getattr(self, 'namespaces', None) if error.elem is None: error.elem = elem if error.source is None: error.source = getattr(self, 'source', None) elif isinstance(error, Exception): message = str(error).strip() if message[0] in '\'"' and message[0] == message[-1]: message = message.strip('\'"') error = XMLSchemaParseError(self, message, elem) elif isinstance(error, str): error = XMLSchemaParseError(self, error, elem) else: msg = "'error' argument must be an exception or a string, not {!r}." raise XMLSchemaTypeError(msg.format(error)) if validation == 'lax': 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) self.errors.append(error) else: raise error
(self, error: Union[str, Exception], elem: Optional[~T] = None, validation: Optional[str] = None) -> NoneType
713,406
xmlschema.validators.schemas
raw_decoder
Returns a generator for decoding a resource.
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)
(self, source: xmlschema.resources.XMLResource, path: Optional[str] = None, schema_path: Optional[str] = None, validation: str = 'lax', namespaces: Optional[~T] = None, **kwargs: Any) -> Iterator[Union[Any, xmlschema.validators.exceptions.XMLSchemaValidationError]]
713,407
xmlschema.validators.schemas
resolve_qname
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.
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}'
(self, qname: str, namespace_imported: bool = True) -> str
713,408
xmlschema.validators.schemas
simple_type_factory
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.
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
(self, elem: Optional[~T], schema: Optional[~T] = None, parent: Optional[xmlschema.validators.xsdbase.XsdComponent] = None) -> xmlschema.validators.simple_types.XsdSimpleType
713,411
xmlschema.validators.schemas
to_objects
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*.
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)
(self, source: Union[~T, NoneType, xmlschema.resources.XMLResource], with_bindings: bool = False, **kwargs: Any) -> Optional[xmlschema.dataobjects.DataElement]