Base modules refactoring for fix ElementTree import

This commit is contained in:
Davide Brunato 2019-10-07 15:31:18 +02:00
parent 7fcacde313
commit b7b6fef418
26 changed files with 201 additions and 190 deletions

View File

@ -10,6 +10,7 @@
#
from .exceptions import XMLSchemaException, XMLSchemaRegexError, XMLSchemaURLError, \
XMLSchemaNamespaceError
from .etree import etree_tostring
from .resources import (
normalize_url, fetch_resource, load_xml_resource, fetch_namespaces,
fetch_schema_locations, fetch_schema, XMLResource

View File

@ -18,9 +18,9 @@ import warnings
from .compat import ordered_dict_class, unicode_type
from .exceptions import XMLSchemaValueError
from .etree import etree_element, lxml_etree_element, etree_register_namespace, lxml_etree_register_namespace
from .namespaces import XSI_NAMESPACE
from .helpers import local_name
from .qnames import local_name
from .etree import etree_element, lxml_etree_element, etree_register_namespace, lxml_etree_register_namespace
from xmlschema.namespaces import NamespaceMapper
ElementData = namedtuple('ElementData', ['tag', 'text', 'content', 'attributes'])

View File

@ -13,8 +13,8 @@ This module contains ElementTree setup and helpers for xmlschema package.
"""
from __future__ import unicode_literals
import sys
import re
import importlib
import re
from collections import Counter
try:
@ -23,10 +23,9 @@ except ImportError:
lxml_etree = None
from .compat import PY3
from .exceptions import XMLSchemaValueError, XMLSchemaTypeError
from .namespaces import XSLT_NAMESPACE, HFP_NAMESPACE, VC_NAMESPACE
from .helpers import get_namespace, get_qname, qname_to_prefixed
from .xpath import ElementPathMixin
from .exceptions import XMLSchemaTypeError, XMLSchemaValueError
from .namespaces import XSLT_NAMESPACE, HFP_NAMESPACE, VC_NAMESPACE, get_namespace
from .qnames import get_qname, qname_to_prefixed
###
# Programmatic import of xml.etree.ElementTree
@ -130,11 +129,6 @@ class SafeXMLParser(PyElementTree.XMLParser):
)
def is_etree_element(elem):
"""More safer test for matching ElementTree elements."""
return hasattr(elem, 'tag') and hasattr(elem, 'attrib') and not isinstance(elem, ElementPathMixin)
def etree_tostring(elem, namespaces=None, indent='', max_lines=None, spaces_for_tab=4, xml_declaration=False):
"""
Serialize an Element tree to a string. Tab characters are replaced by whitespaces.
@ -267,21 +261,6 @@ def etree_getpath(elem, root, namespaces=None, relative=True, add_position=False
return path
def etree_last_child(elem):
"""Returns the last child of the element, ignoring children that are lxml comments."""
for child in reversed(elem):
if not callable(child.tag):
return child
def etree_child_index(elem, child):
"""Return the index or raise ValueError if it is not a *child* of *elem*."""
for index in range(len(elem)):
if elem[index] is child:
return index
raise XMLSchemaValueError("%r is not a child of %r" % (child, elem))
def etree_elements_assert_equal(elem, other, strict=True, skip_comments=True):
"""
Tests the equality of two XML Element trees.

View File

@ -11,116 +11,19 @@
"""
This module contains various helper functions and classes.
"""
import re
from decimal import Decimal
from .compat import string_base_type
from .exceptions import XMLSchemaValueError, XMLSchemaTypeError
from .exceptions import XMLSchemaValueError
from .qnames import XSD_ANNOTATION
from .xpath import ElementPathMixin
XSD_FINAL_ATTRIBUTE_VALUES = {'restriction', 'extension', 'list', 'union'}
NAMESPACE_PATTERN = re.compile(r'{([^}]*)}')
def get_namespace(name):
try:
return NAMESPACE_PATTERN.match(name).group(1)
except (AttributeError, TypeError):
return ''
def get_qname(uri, name):
"""
Returns an expanded QName from URI and local part. If any argument has boolean value
`False` or if the name is already an expanded QName, returns the *name* argument.
:param uri: namespace URI
:param name: local or qualified name
:return: string or the name argument
"""
if not uri or not name or name[0] in ('{', '.', '/', '['):
return name
else:
return '{%s}%s' % (uri, name)
def local_name(qname):
"""
Return the local part of an expanded QName or a prefixed name. If the name
is `None` or empty returns the *name* argument.
:param qname: an expanded QName or a prefixed name or a local name.
"""
try:
if qname[0] == '{':
_, qname = qname.split('}')
elif ':' in qname:
_, qname = qname.split(':')
except IndexError:
return ''
except ValueError:
raise XMLSchemaValueError("the argument 'qname' has a wrong format: %r" % qname)
except TypeError:
if qname is None:
return qname
raise XMLSchemaTypeError("the argument 'qname' must be a string-like object or None")
else:
return qname
def qname_to_prefixed(qname, namespaces):
"""
Transforms a fully qualified name into a prefixed name using a namespace map.
Returns the *qname* argument if it's not a fully qualified name or if it has
boolean value `False`.
:param qname: an extended QName or a local name.
:param namespaces: a map from prefixes to namespace URIs.
:return: a QName in prefixed format or a local name.
"""
if not qname:
return qname
namespace = get_namespace(qname)
for prefix, uri in sorted(filter(lambda x: x[1] == namespace, namespaces.items()), reverse=True):
if not uri:
return '%s:%s' % (prefix, qname) if prefix else qname
elif prefix:
return qname.replace('{%s}' % uri, '%s:' % prefix)
else:
return qname.replace('{%s}' % uri, '')
else:
return qname
def qname_to_extended(qname, namespaces):
"""
Converts a QName in prefixed format or a local name to the extended QName format.
:param qname: a QName in prefixed format or a local name.
:param namespaces: a map from prefixes to namespace URIs.
:return: a QName in extended format or a local name.
"""
try:
if qname[0] == '{' or not namespaces:
return qname
except IndexError:
return qname
try:
prefix, name = qname.split(':', 1)
except ValueError:
if not namespaces.get(''):
return qname
else:
return '{%s}%s' % (namespaces[''], qname)
else:
try:
uri = namespaces[prefix]
except KeyError:
return qname
else:
return u'{%s}%s' % (uri, name) if uri else name
def is_etree_element(elem):
"""More safer test for matching ElementTree elements."""
return hasattr(elem, 'tag') and hasattr(elem, 'attrib') and not isinstance(elem, ElementPathMixin)
def get_xsd_annotation(elem):

View File

@ -12,9 +12,9 @@
This module contains namespace definitions for W3C core standards and namespace related classes.
"""
from __future__ import unicode_literals
import re
from .compat import MutableMapping, Mapping
from .helpers import get_namespace
XSD_NAMESPACE = 'http://www.w3.org/2001/XMLSchema'
"URI of the XML Schema Definition namespace (xs|xsd)"
@ -42,6 +42,16 @@ VC_NAMESPACE = 'http://www.w3.org/2007/XMLSchema-versioning'
"URI of the XML Schema Versioning namespace (vc)"
NAMESPACE_PATTERN = re.compile(r'{([^}]*)}')
def get_namespace(name):
try:
return NAMESPACE_PATTERN.match(name).group(1)
except (AttributeError, TypeError):
return ''
class NamespaceResourcesMap(MutableMapping):
"""
Dictionary for storing information about namespace resources. The values are

View File

@ -9,9 +9,11 @@
# @author Davide Brunato <brunato@sissa.it>
#
"""
This module contains qualified names constants.
This module contains qualified names constants and helpers.
"""
from __future__ import unicode_literals
from .exceptions import XMLSchemaTypeError, XMLSchemaValueError
from .namespaces import get_namespace
VC_TEMPLATE = '{http://www.w3.org/2007/XMLSchema-versioning}%s'
XML_TEMPLATE = '{http://www.w3.org/XML/1998/namespace}%s'
@ -181,3 +183,98 @@ XSD_DATE_TIME_STAMP = XSD_TEMPLATE % 'dateTimeStamp'
XSD_DAY_TIME_DURATION = XSD_TEMPLATE % 'dayTimeDuration'
XSD_YEAR_MONTH_DURATION = XSD_TEMPLATE % 'yearMonthDuration'
XSD_ERROR = XSD_TEMPLATE % 'error'
def get_qname(uri, name):
"""
Returns an expanded QName from URI and local part. If any argument has boolean value
`False` or if the name is already an expanded QName, returns the *name* argument.
:param uri: namespace URI
:param name: local or qualified name
:return: string or the name argument
"""
if not uri or not name or name[0] in ('{', '.', '/', '['):
return name
else:
return '{%s}%s' % (uri, name)
def local_name(qname):
"""
Return the local part of an expanded QName or a prefixed name. If the name
is `None` or empty returns the *name* argument.
:param qname: an expanded QName or a prefixed name or a local name.
"""
try:
if qname[0] == '{':
_, qname = qname.split('}')
elif ':' in qname:
_, qname = qname.split(':')
except IndexError:
return ''
except ValueError:
raise XMLSchemaValueError("the argument 'qname' has a wrong format: %r" % qname)
except TypeError:
if qname is None:
return qname
raise XMLSchemaTypeError("the argument 'qname' must be a string-like object or None")
else:
return qname
def qname_to_prefixed(qname, namespaces):
"""
Transforms a fully qualified name into a prefixed name using a namespace map.
Returns the *qname* argument if it's not a fully qualified name or if it has
boolean value `False`.
:param qname: an extended QName or a local name.
:param namespaces: a map from prefixes to namespace URIs.
:return: a QName in prefixed format or a local name.
"""
if not qname:
return qname
namespace = get_namespace(qname)
for prefix, uri in sorted(filter(lambda x: x[1] == namespace, namespaces.items()), reverse=True):
if not uri:
return '%s:%s' % (prefix, qname) if prefix else qname
elif prefix:
return qname.replace('{%s}' % uri, '%s:' % prefix)
else:
return qname.replace('{%s}' % uri, '')
else:
return qname
def qname_to_extended(qname, namespaces):
"""
Converts a QName in prefixed format or a local name to the extended QName format.
:param qname: a QName in prefixed format or a local name.
:param namespaces: a map from prefixes to namespace URIs.
:return: a QName in extended format or a local name.
"""
try:
if qname[0] == '{' or not namespaces:
return qname
except IndexError:
return qname
try:
prefix, name = qname.split(':', 1)
except ValueError:
if not namespaces.get(''):
return qname
else:
return '{%s}%s' % (namespaces[''], qname)
else:
try:
uri = namespaces[prefix]
except KeyError:
return qname
else:
return u'{%s}%s' % (uri, name) if uri else name

View File

@ -18,9 +18,9 @@ from .compat import (
pathname2url, URLError, uses_relative
)
from .exceptions import XMLSchemaTypeError, XMLSchemaValueError, XMLSchemaURLError, XMLSchemaOSError
from .namespaces import get_namespace
from .qnames import XSI_SCHEMA_LOCATION, XSI_NONS_SCHEMA_LOCATION
from .helpers import get_namespace
from .etree import ElementTree, PyElementTree, SafeXMLParser, is_etree_element, etree_tostring
from .etree import ElementTree, PyElementTree, SafeXMLParser, etree_tostring
DEFUSE_MODES = ('always', 'remote', 'never')
@ -285,7 +285,7 @@ class XMLResource(object):
def _fromsource(self, source):
url, lazy = None, self._lazy
if is_etree_element(source):
if hasattr(source, 'tag'):
self._lazy = False
return source, None, None, None # Source is already an Element --> nothing to load
elif isinstance(source, string_base_type):
@ -344,7 +344,7 @@ class XMLResource(object):
except (AttributeError, TypeError):
pass
else:
if is_etree_element(root):
if hasattr(root, 'tag'):
self._lazy = False
return root, source, None, None

View File

@ -20,13 +20,11 @@ import xmlschema
from xmlschema import XMLSchema
from xmlschema.compat import urlopen, URLError, unicode_type
from xmlschema.exceptions import XMLSchemaValueError
from xmlschema.etree import (
is_etree_element, etree_element, etree_register_namespace, etree_elements_assert_equal
)
from xmlschema.resources import fetch_namespaces
from xmlschema.qnames import XSD_SCHEMA
from xmlschema.helpers import get_namespace
from xmlschema.namespaces import XSD_NAMESPACE
from xmlschema.namespaces import XSD_NAMESPACE, get_namespace
from xmlschema.etree import etree_element, etree_register_namespace, etree_elements_assert_equal
from xmlschema.resources import fetch_namespaces
from xmlschema.helpers import is_etree_element
def has_network_access(*locations):

View File

@ -20,10 +20,10 @@ import xml.etree.ElementTree as ElementTree
from xmlschema import XMLSchema, XMLSchemaParseError
from xmlschema.etree import etree_element, prune_etree
from xmlschema.namespaces import XSD_NAMESPACE, XSI_NAMESPACE
from xmlschema.helpers import get_xsd_annotation, get_namespace, get_qname, local_name, \
qname_to_prefixed, get_xsd_derivation_attribute, count_digits
from xmlschema.namespaces import XSD_NAMESPACE, XSI_NAMESPACE, get_namespace
from xmlschema.qnames import XSI_TYPE, XSD_SCHEMA, XSD_ELEMENT, XSD_SIMPLE_TYPE, XSD_ANNOTATION
from xmlschema.qnames import get_qname, local_name, qname_to_prefixed
from xmlschema.helpers import get_xsd_annotation, get_xsd_derivation_attribute, count_digits
class TestHelpers(unittest.TestCase):

View File

@ -26,8 +26,9 @@ from xmlschema import (
)
from xmlschema.tests import casepath
from xmlschema.compat import urlopen, urlsplit, uses_relative, StringIO
from xmlschema.etree import ElementTree, PyElementTree, lxml_etree, is_etree_element, \
from xmlschema.etree import ElementTree, PyElementTree, lxml_etree, \
etree_element, py_etree_element
from xmlschema.helpers import is_etree_element
def is_windows_path(path):

View File

@ -15,9 +15,10 @@ import unittest
from xmlschema import XMLSchemaEncodeError, XMLSchemaValidationError
from xmlschema.converters import UnorderedConverter
from xmlschema.compat import unicode_type, ordered_dict_class
from xmlschema.etree import etree_element, etree_tostring, is_etree_element, ElementTree
from xmlschema.qnames import local_name
from xmlschema.etree import etree_element, etree_tostring, ElementTree
from xmlschema.validators.exceptions import XMLSchemaChildrenValidationError
from xmlschema.helpers import local_name
from xmlschema.helpers import is_etree_element
from xmlschema.tests import XsdValidatorTestCase
from xmlschema.validators import XMLSchema11

View File

@ -11,7 +11,6 @@
from __future__ import unicode_literals
from elementpath import datatypes, XPath2Parser, XPathContext, ElementPathError
from ..etree import ElementTree
from ..qnames import XSD_ASSERT
from ..xpath import ElementPathMixin, XMLSchemaProxy
@ -49,7 +48,7 @@ class XsdAssert(XsdComponent, ElementPathMixin):
self.parse_error("base_type=%r is not a complexType definition" % self.base_type)
else:
try:
self.path = self.elem.attrib['test']
self.path = self.elem.attrib['test'].strip()
except KeyError as err:
self.parse_error(str(err), elem=self.elem)
@ -87,7 +86,7 @@ class XsdAssert(XsdComponent, ElementPathMixin):
self.parse_error(err, elem=self.elem)
self.token = self.parser.parse('true()')
def __call__(self, elem, value=None, source=None, **kwargs):
def __call__(self, elem, value=None, source=None, namespaces=None, **kwargs):
if value is not None:
self.parser.variables['value'] = self.base_type.text_decode(value)
@ -96,6 +95,11 @@ class XsdAssert(XsdComponent, ElementPathMixin):
else:
context = XPathContext(root=source.root, item=elem)
default_namespace = self.parser.namespaces['']
if namespaces and '' in namespaces:
self.parser.namespaces[''] = namespaces['']
try:
if not self.token.evaluate(context.copy()):
msg = "expression is not true with test path %r."
@ -103,6 +107,8 @@ class XsdAssert(XsdComponent, ElementPathMixin):
except ElementPathError as err:
yield XMLSchemaValidationError(self, obj=elem, reason=str(err))
self.parser.namespaces[''] = default_namespace
# For implementing ElementPathMixin
def __iter__(self):
if not self.parent.has_simple_content():

View File

@ -19,8 +19,9 @@ from ..compat import MutableMapping, ordered_dict_class
from ..exceptions import XMLSchemaAttributeError, XMLSchemaTypeError, XMLSchemaValueError
from ..qnames import XSD_ANNOTATION, XSD_ANY_SIMPLE_TYPE, XSD_SIMPLE_TYPE, \
XSD_ATTRIBUTE_GROUP, XSD_COMPLEX_TYPE, XSD_RESTRICTION, XSD_EXTENSION, \
XSD_SEQUENCE, XSD_ALL, XSD_CHOICE, XSD_ATTRIBUTE, XSD_ANY_ATTRIBUTE
from ..helpers import get_namespace, get_qname, get_xsd_form_attribute
XSD_SEQUENCE, XSD_ALL, XSD_CHOICE, XSD_ATTRIBUTE, XSD_ANY_ATTRIBUTE, \
get_namespace, get_qname
from ..helpers import get_xsd_form_attribute
from ..namespaces import XSI_NAMESPACE
from .exceptions import XMLSchemaValidationError

View File

@ -25,8 +25,21 @@ from elementpath import datatypes
from ..compat import PY3, long_type, unicode_type
from ..exceptions import XMLSchemaValueError
from ..qnames import *
from ..etree import etree_element, is_etree_element
from ..qnames import XSD_LENGTH, XSD_MIN_LENGTH, XSD_MAX_LENGTH, XSD_ENUMERATION, \
XSD_PATTERN, XSD_WHITE_SPACE, XSD_MIN_INCLUSIVE, XSD_MIN_EXCLUSIVE, XSD_MAX_INCLUSIVE, \
XSD_MAX_EXCLUSIVE, XSD_TOTAL_DIGITS, XSD_FRACTION_DIGITS, XSD_EXPLICIT_TIMEZONE, \
XSD_STRING, XSD_NORMALIZED_STRING, XSD_NAME, XSD_NCNAME, XSD_QNAME, XSD_TOKEN, \
XSD_NMTOKEN, XSD_ID, XSD_IDREF, XSD_LANGUAGE, XSD_DECIMAL, XSD_DOUBLE, XSD_FLOAT, \
XSD_INTEGER, XSD_BYTE, XSD_SHORT, XSD_INT, XSD_LONG, XSD_UNSIGNED_BYTE, \
XSD_UNSIGNED_SHORT, XSD_UNSIGNED_INT, XSD_UNSIGNED_LONG, XSD_POSITIVE_INTEGER, \
XSD_NEGATIVE_INTEGER, XSD_NON_NEGATIVE_INTEGER, XSD_NON_POSITIVE_INTEGER, \
XSD_GDAY, XSD_GMONTH, XSD_GMONTH_DAY, XSD_GYEAR, XSD_GYEAR_MONTH, XSD_TIME, XSD_DATE, \
XSD_DATETIME, XSD_DATE_TIME_STAMP, XSD_ENTITY, XSD_ANY_URI, XSD_BOOLEAN, \
XSD_DURATION, XSD_DAY_TIME_DURATION, XSD_YEAR_MONTH_DURATION, XSD_BASE64_BINARY, \
XSD_HEX_BINARY, XSD_NOTATION_TYPE, XSD_ERROR, XSD_ASSERTION, XSD_SIMPLE_TYPE, \
XSD_COMPLEX_TYPE, XSD_ANY_TYPE, XSD_ANY_ATOMIC_TYPE, XSD_ANY_SIMPLE_TYPE
from ..etree import etree_element
from ..helpers import is_etree_element
from .exceptions import XMLSchemaValidationError
from .facets import XSD_10_FACETS_BUILDERS, XSD_11_FACETS_BUILDERS
from .simple_types import XsdSimpleType, XsdAtomicBuiltin

View File

@ -10,12 +10,12 @@
#
from __future__ import unicode_literals
from ..exceptions import XMLSchemaTypeError, XMLSchemaValueError
from ..qnames import XSD_ANNOTATION, XSD_GROUP, XSD_ATTRIBUTE_GROUP, XSD_SEQUENCE, XSD_ALL, \
XSD_CHOICE, XSD_ANY_ATTRIBUTE, XSD_ATTRIBUTE, XSD_COMPLEX_CONTENT, XSD_RESTRICTION, \
XSD_COMPLEX_TYPE, XSD_EXTENSION, XSD_ANY_TYPE, XSD_SIMPLE_CONTENT, XSD_ANY_SIMPLE_TYPE, \
XSD_OPEN_CONTENT, XSD_ASSERT, XSI_TYPE
from ..helpers import get_qname, local_name, qname_to_extended, get_xsd_derivation_attribute
from ..exceptions import XMLSchemaValueError
from ..qnames import XSD_ANNOTATION, XSD_GROUP, XSD_ATTRIBUTE_GROUP, XSD_SEQUENCE, \
XSD_ALL, XSD_CHOICE, XSD_ANY_ATTRIBUTE, XSD_ATTRIBUTE, XSD_COMPLEX_CONTENT, \
XSD_RESTRICTION, XSD_COMPLEX_TYPE, XSD_EXTENSION, XSD_ANY_TYPE, XSD_SIMPLE_CONTENT, \
XSD_ANY_SIMPLE_TYPE, XSD_OPEN_CONTENT, XSD_ASSERT, get_qname, local_name
from ..helpers import get_xsd_derivation_attribute
from .exceptions import XMLSchemaValidationError, XMLSchemaDecodeError
from .xsdbase import XsdType, ValidationMixin

View File

@ -20,12 +20,11 @@ from elementpath.datatypes import AbstractDateTime, Duration
from ..exceptions import XMLSchemaAttributeError
from ..qnames import XSD_ANNOTATION, XSD_GROUP, XSD_SEQUENCE, XSD_ALL, \
XSD_CHOICE, XSD_ATTRIBUTE_GROUP, XSD_COMPLEX_TYPE, XSD_SIMPLE_TYPE, \
XSD_ALTERNATIVE, XSD_ELEMENT, XSD_ANY_TYPE, XSD_UNIQUE, \
XSD_KEY, XSD_KEYREF, XSI_NIL, XSI_TYPE, XSD_ID, XSD_ERROR
from ..helpers import get_qname, get_xsd_derivation_attribute, \
get_xsd_form_attribute, ParticleCounter
XSD_ALTERNATIVE, XSD_ELEMENT, XSD_ANY_TYPE, XSD_UNIQUE, XSD_KEY, \
XSD_KEYREF, XSI_NIL, XSI_TYPE, XSD_ID, XSD_ERROR, get_qname
from ..etree import etree_element
from ..helpers import strictly_equal
from ..helpers import get_xsd_derivation_attribute, get_xsd_form_attribute, \
ParticleCounter, strictly_equal
from ..converters import ElementData, raw_xml_encode, XMLSchemaConverter
from ..xpath import XMLSchemaProxy, ElementPathMixin

View File

@ -15,8 +15,9 @@ from __future__ import unicode_literals
from ..compat import PY3, string_base_type
from ..exceptions import XMLSchemaException, XMLSchemaWarning, XMLSchemaValueError
from ..etree import etree_tostring, is_etree_element, etree_getpath
from ..helpers import qname_to_prefixed
from ..qnames import qname_to_prefixed
from ..etree import etree_tostring, etree_getpath
from ..helpers import is_etree_element
from ..resources import XMLResource

View File

@ -17,11 +17,10 @@ from collections import Counter
from ..compat import string_base_type
from ..exceptions import XMLSchemaKeyError, XMLSchemaTypeError, XMLSchemaValueError, XMLSchemaWarning
from ..namespaces import XSD_NAMESPACE
from ..qnames import XSD_REDEFINE, XSD_OVERRIDE, XSD_NOTATION, XSD_ANY_TYPE, XSD_SIMPLE_TYPE, \
XSD_COMPLEX_TYPE, XSD_GROUP, XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, XSD_ELEMENT, XSI_TYPE
from ..helpers import get_qname, local_name, qname_to_extended
from ..namespaces import NamespaceResourcesMap
from ..namespaces import XSD_NAMESPACE, NamespaceResourcesMap
from ..qnames import XSD_REDEFINE, XSD_OVERRIDE, XSD_NOTATION, XSD_ANY_TYPE, \
XSD_SIMPLE_TYPE, XSD_COMPLEX_TYPE, XSD_GROUP, XSD_ATTRIBUTE, XSD_ATTRIBUTE_GROUP, \
XSD_ELEMENT, XSI_TYPE, get_qname, local_name, qname_to_extended
from . import XMLSchemaNotBuiltError, XMLSchemaModelError, XMLSchemaModelDepthError, \
XsdValidator, XsdComponent, XsdAttribute, XsdSimpleType, XsdComplexType, XsdElement, \

View File

@ -18,8 +18,7 @@ from ..compat import unicode_type
from ..exceptions import XMLSchemaValueError
from ..etree import etree_element
from ..qnames import XSD_ANNOTATION, XSD_GROUP, XSD_SEQUENCE, XSD_ALL, \
XSD_CHOICE, XSD_ELEMENT, XSD_ANY, XSI_TYPE
from xmlschema.helpers import get_qname, local_name
XSD_CHOICE, XSD_ELEMENT, XSD_ANY, XSI_TYPE, get_qname, local_name
from .exceptions import XMLSchemaValidationError, XMLSchemaChildrenValidationError, \
XMLSchemaTypeTableWarning

View File

@ -17,8 +17,8 @@ from collections import Counter
from elementpath import Selector, XPath1Parser, ElementPathError
from ..exceptions import XMLSchemaValueError
from ..qnames import XSD_ANNOTATION, XSD_QNAME, XSD_UNIQUE, XSD_KEY, XSD_KEYREF, XSD_SELECTOR, XSD_FIELD
from ..helpers import get_qname, qname_to_prefixed, qname_to_extended
from ..qnames import XSD_ANNOTATION, XSD_QNAME, XSD_UNIQUE, XSD_KEY, XSD_KEYREF, \
XSD_SELECTOR, XSD_FIELD, get_qname, qname_to_prefixed, qname_to_extended
from ..etree import etree_getpath
from ..regex import get_python_regex
@ -152,9 +152,10 @@ class XsdIdentity(XsdComponent):
"""
Get fields for a schema or instance context element.
:param context: Context Element or XsdElement
:param decoders: Context schema fields decoders.
:return: A tuple with field values. An empty field is replaced by `None`.
:param context: context Element or XsdElement
:param namespaces: is an optional mapping from namespace prefix to URI.
:param decoders: context schema fields decoders.
:return: a tuple with field values. An empty field is replaced by `None`.
"""
fields = []
for k, field in enumerate(self.fields):

View File

@ -10,10 +10,7 @@
#
from __future__ import unicode_literals
from ..exceptions import XMLSchemaValueError
from ..qnames import XSD_NOTATION
from ..helpers import get_qname
from ..qnames import XSD_NOTATION, get_qname
from .xsdbase import XsdComponent

View File

@ -938,6 +938,7 @@ class XMLSchemaBase(XsdValidator, ValidationMixin, ElementPathMixin):
import_error = None
for url in locations:
try:
# print("Import namespace ", namespace, url)
self.import_schema(namespace, url, self.base_url)
except (OSError, IOError) as err:
# It's not an error if the location access fails (ref. section 4.2.6.2):

View File

@ -23,8 +23,8 @@ from ..qnames import XSD_ANY_TYPE, XSD_SIMPLE_TYPE, XSD_ANY_ATOMIC_TYPE, \
XSD_LENGTH, XSD_MIN_LENGTH, XSD_MAX_LENGTH, XSD_WHITE_SPACE, XSD_LIST, \
XSD_ANY_SIMPLE_TYPE, XSD_UNION, XSD_RESTRICTION, XSD_ANNOTATION, XSD_ASSERTION, \
XSD_ID, XSD_IDREF, XSD_FRACTION_DIGITS, XSD_TOTAL_DIGITS, XSD_EXPLICIT_TIMEZONE, \
XSD_ERROR, XSD_ASSERT
from ..helpers import get_qname, local_name, get_xsd_derivation_attribute
XSD_ERROR, XSD_ASSERT, get_qname, local_name
from ..helpers import get_xsd_derivation_attribute
from .exceptions import XMLSchemaValidationError, XMLSchemaEncodeError, \
XMLSchemaDecodeError, XMLSchemaParseError

View File

@ -14,9 +14,9 @@ This module contains classes for XML Schema wildcards.
from __future__ import unicode_literals
from ..exceptions import XMLSchemaValueError
from ..qnames import XSD_ANY, XSD_ANY_ATTRIBUTE, XSD_OPEN_CONTENT, XSD_DEFAULT_OPEN_CONTENT
from ..helpers import get_namespace
from ..namespaces import XSI_NAMESPACE
from ..qnames import XSD_ANY, XSD_ANY_ATTRIBUTE, XSD_OPEN_CONTENT, \
XSD_DEFAULT_OPEN_CONTENT, get_namespace
from ..xpath import XMLSchemaProxy, ElementPathMixin
from .exceptions import XMLSchemaNotBuiltError

View File

@ -17,9 +17,10 @@ import re
from ..compat import PY3, string_base_type, unicode_type
from ..exceptions import XMLSchemaValueError, XMLSchemaTypeError
from ..qnames import XSD_ANNOTATION, XSD_APPINFO, XSD_DOCUMENTATION, XML_LANG, \
XSD_ANY_TYPE, XSD_ANY_SIMPLE_TYPE, XSD_ANY_ATOMIC_TYPE, XSD_ID, XSD_OVERRIDE
from ..helpers import get_qname, local_name, qname_to_prefixed
from ..etree import etree_tostring, is_etree_element
XSD_ANY_TYPE, XSD_ANY_SIMPLE_TYPE, XSD_ANY_ATOMIC_TYPE, XSD_ID, XSD_OVERRIDE, \
get_qname, local_name, qname_to_prefixed
from ..etree import etree_tostring
from ..helpers import is_etree_element
from .exceptions import XMLSchemaParseError, XMLSchemaValidationError, \
XMLSchemaDecodeError, XMLSchemaEncodeError

View File

@ -120,6 +120,9 @@ class XMLSchemaProxy(AbstractSchemaProxy):
except KeyError:
return None
def find(self, path, namespaces=None):
return self._schema.find(path, namespaces)
def is_instance(self, obj, type_qname):
xsd_type = self._schema.maps.types[type_qname]
try: