How to use the xmlschema.etree.etree_element function in xmlschema

To help you get started, we’ve selected a few xmlschema examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sissaschool / xmlschema / xmlschema / validators / elements.py View on Github external
def get_type(self, elem, inherited=None):
        if not self.alternatives:
            return self.type

        if isinstance(elem, ElementData):
            if elem.attributes:
                attrib = {k: raw_xml_encode(v) for k, v in elem.attributes.items()}
                elem = etree_element(elem.tag, attrib=attrib)
            else:
                elem = etree_element(elem.tag)

        if inherited:
            dummy = etree_element('_dummy_element', attrib=inherited)
            dummy.attrib.update(elem.attrib)

            for alt in filter(lambda x: x.type is not None, self.alternatives):
                if alt.token is None or alt.test(elem) or alt.test(dummy):
                    return alt.type
        else:
            for alt in filter(lambda x: x.type is not None, self.alternatives):
                if alt.token is None or alt.test(elem):
                    return alt.type

        return self.type
github sissaschool / xmlschema / xmlschema / validators / elements.py View on Github external
def get_type(self, elem, inherited=None):
        if not self.alternatives:
            return self.type

        if isinstance(elem, ElementData):
            if elem.attributes:
                attrib = {k: raw_xml_encode(v) for k, v in elem.attributes.items()}
                elem = etree_element(elem.tag, attrib=attrib)
            else:
                elem = etree_element(elem.tag)

        if inherited:
            dummy = etree_element('_dummy_element', attrib=inherited)
            dummy.attrib.update(elem.attrib)

            for alt in filter(lambda x: x.type is not None, self.alternatives):
                if alt.token is None or alt.test(elem) or alt.test(dummy):
                    return alt.type
        else:
            for alt in filter(lambda x: x.type is not None, self.alternatives):
                if alt.token is None or alt.test(elem):
                    return alt.type

        return self.type
github sissaschool / xmlschema / xmlschema / validators / schema.py View on Github external
def create_empty_content_group(self, parent, model='sequence'):
        if model == 'sequence':
            group_elem = etree_element(XSD_SEQUENCE)
        elif model == 'choice':
            group_elem = etree_element(XSD_CHOICE)
        elif model == 'all':
            group_elem = etree_element(XSD_ALL)
        else:
            raise XMLSchemaValueError("'model' argument must be (sequence | choice | all)")

        group_elem.text = '\n    '
        return self.BUILDERS.group_class(group_elem, self, parent)
github sissaschool / xmlschema / xmlschema / validators / builtins.py View on Github external
},  # any integer value
    {
        'name': XSD_LONG,
        'python_type': int if PY3 else (long_type, int),
        'base_type': XSD_INTEGER,
        'facets': [long_validator,
                   etree_element(XSD_MIN_INCLUSIVE, value='-9223372036854775808'),
                   etree_element(XSD_MAX_INCLUSIVE, value='9223372036854775807')]
    },  # signed 128 bit value
    {
        'name': XSD_INT,
        'python_type': int,
        'base_type': XSD_LONG,
        'facets': [int_validator,
                   etree_element(XSD_MIN_INCLUSIVE, value='-2147483648'),
                   etree_element(XSD_MAX_INCLUSIVE, value='2147483647')]
    },  # signed 64 bit value
    {
        'name': XSD_SHORT,
        'python_type': int,
        'base_type': XSD_INT,
        'facets': [short_validator,
                   etree_element(XSD_MIN_INCLUSIVE, value='-32768'),
                   etree_element(XSD_MAX_INCLUSIVE, value='32767')]
    },  # signed 32 bit value
    {
        'name': XSD_BYTE,
        'python_type': int,
        'base_type': XSD_SHORT,
        'facets': [byte_validator,
                   etree_element(XSD_MIN_INCLUSIVE, value='-128'),
                   etree_element(XSD_MAX_INCLUSIVE, value='127')]
github sissaschool / xmlschema / xmlschema / validators / builtins.py View on Github external
'to_python': datatypes.GregorianYear.fromstring,
    },  # [-][Y*]YYYY
    {
        'name': XSD_GYEAR_MONTH,
        'python_type': (unicode_type, str, datatypes.GregorianYearMonth),
        'admitted_facets': DATETIME_FACETS,
        'facets': [COLLAPSE_WHITE_SPACE_ELEMENT],
        'to_python': datatypes.GregorianYearMonth.fromstring,
    },  # [-][Y*]YYYY-MM
    # --- Datetime derived types (XSD 1.1) ---
    {
        'name': XSD_DATE_TIME_STAMP,
        'python_type': (unicode_type, str),
        'base_type': XSD_DATETIME,
        'to_python': datatypes.DateTime.fromstring,
        'facets': [etree_element(XSD_EXPLICIT_TIMEZONE, value='required')],
    },  # [-][Y*]YYYY-MM-DD[Thh:mm:ss] with required timezone
    {
        'name': XSD_DAY_TIME_DURATION,
        'python_type': (unicode_type, str),
        'base_type': XSD_DURATION,
        'to_python': datatypes.DayTimeDuration.fromstring,
    },  # PnYnMnDTnHnMnS with month an year equal to 0
    {
        'name': XSD_YEAR_MONTH_DURATION,
        'python_type': (unicode_type, str),
        'base_type': XSD_DURATION,
        'to_python': datatypes.YearMonthDuration.fromstring,
    },  # PnYnMnDTnHnMnS with day and time equals to 0
    # --- xs:error primitive type (XSD 1.1) ---
    {
        'name': XSD_ERROR,
github sissaschool / xmlschema / xmlschema / validators / schema.py View on Github external
from .wildcards import XsdAnyElement, XsdAnyAttribute, Xsd11AnyElement, \
    Xsd11AnyAttribute, XsdDefaultOpenContent
from .globals_ import XsdGlobals

logger = logging.getLogger('xmlschema')
logging.basicConfig(format='[%(levelname)s] %(message)s')

XSD_VERSION_PATTERN = re.compile(r'^\d+\.\d+$')

# Elements for building dummy groups
ATTRIBUTE_GROUP_ELEMENT = etree_element(XSD_ATTRIBUTE_GROUP)
ANY_ATTRIBUTE_ELEMENT = etree_element(
    XSD_ANY_ATTRIBUTE, attrib={'namespace': '##any', 'processContents': 'lax'}
)
SEQUENCE_ELEMENT = etree_element(XSD_SEQUENCE)
ANY_ELEMENT = etree_element(
    XSD_ANY,
    attrib={
        'namespace': '##any',
        'processContents': 'lax',
        'minOccurs': '0',
        'maxOccurs': 'unbounded'
    })


class XMLSchemaMeta(ABCMeta):

    def __new__(mcs, name, bases, dict_):

        def get_attribute(attr, *args):
            for obj in args:
                if hasattr(obj, attr):
github sissaschool / xmlschema / xmlschema / validators / builtins.py View on Github external
elem=etree_element(XSD_SIMPLE_TYPE, name=XSD_ANY_ATOMIC_TYPE),
        schema=meta_schema,
        parent=None,
        name=XSD_ANY_ATOMIC_TYPE,
        base_type=xsd_types[XSD_ANY_SIMPLE_TYPE]
    )

    for item in builtin_types:
        item = item.copy()
        name = item['name']
        try:
            elem, schema = xsd_types[name]
        except KeyError:
            # If builtin type element is missing create a dummy element. Necessary for the
            # meta-schema XMLSchema.xsd of XSD 1.1, that not includes builtins declarations.
            elem = etree_element(XSD_SIMPLE_TYPE, name=name, id=name)
        else:
            if schema is not meta_schema:
                raise XMLSchemaValueError("loaded entry schema doesn't match meta_schema!")

        if 'base_type' in item:
            base_type = item['base_type'] = xsd_types[item['base_type']]
        else:
            base_type = None

        facets = item.pop('facets', None)
        builtin_type = atomic_builtin_class(elem, meta_schema, **item)
        if isinstance(facets, (list, tuple)):
            built_facets = builtin_type.facets
            for e in facets:
                if is_etree_element(e):
                    cls = facets_map[e.tag]
github sissaschool / xmlschema / xmlschema / validators / builtins.py View on Github external
def boolean_to_python(s):
    if s in ('true', '1'):
        return True
    elif s in ('false', '0'):
        return False
    else:
        raise XMLSchemaValueError('not a boolean value: %r' % s)


def python_to_boolean(obj):
    return unicode_type(obj).lower()


#
# Element facets instances for builtin types.
PRESERVE_WHITE_SPACE_ELEMENT = etree_element(XSD_WHITE_SPACE, value='preserve')
COLLAPSE_WHITE_SPACE_ELEMENT = etree_element(XSD_WHITE_SPACE, value='collapse')
REPLACE_WHITE_SPACE_ELEMENT = etree_element(XSD_WHITE_SPACE, value='replace')


XSD_COMMON_BUILTIN_TYPES = (
    # ***********************
    # *** Primitive types ***
    # ***********************

    # --- String Types ---
    {
        'name': XSD_STRING,
        'python_type': (unicode_type, str),
        'admitted_facets': STRING_FACETS,
        'facets': [PRESERVE_WHITE_SPACE_ELEMENT],
    },  # character string
github sissaschool / xmlschema / xmlschema / validators / schema.py View on Github external
from .elements import XsdElement, Xsd11Element
from .wildcards import XsdAnyElement, XsdAnyAttribute, Xsd11AnyElement, \
    Xsd11AnyAttribute, XsdDefaultOpenContent
from .globals_ import XsdGlobals

logger = logging.getLogger('xmlschema')
logging.basicConfig(format='[%(levelname)s] %(message)s')

XSD_VERSION_PATTERN = re.compile(r'^\d+\.\d+$')

# Elements for building dummy groups
ATTRIBUTE_GROUP_ELEMENT = etree_element(XSD_ATTRIBUTE_GROUP)
ANY_ATTRIBUTE_ELEMENT = etree_element(
    XSD_ANY_ATTRIBUTE, attrib={'namespace': '##any', 'processContents': 'lax'}
)
SEQUENCE_ELEMENT = etree_element(XSD_SEQUENCE)
ANY_ELEMENT = etree_element(
    XSD_ANY,
    attrib={
        'namespace': '##any',
        'processContents': 'lax',
        'minOccurs': '0',
        'maxOccurs': 'unbounded'
    })


class XMLSchemaMeta(ABCMeta):

    def __new__(mcs, name, bases, dict_):

        def get_attribute(attr, *args):
            for obj in args:
github sissaschool / xmlschema / xmlschema / validators / groups.py View on Github external
if model.element is not None:
            for particle, occurs, expected in model.stop():
                errors.append((index - cdata_index + 1, particle, occurs, expected))

        if children:
            if children[-1].tail is None:
                children[-1].tail = padding[:-indent] or '\n'
            else:
                children[-1].tail = children[-1].tail.strip() + (padding[:-indent] or '\n')

        cdata_not_allowed = not self.mixed and not_whitespace(text) and self and \
            (len(self) > 1 or not isinstance(self[0], XsdAnyElement))

        if validation != 'skip' and (errors or cdata_not_allowed or wrong_content_type):
            attrib = {k: unicode_type(v) for k, v in element_data.attributes.items()}
            if validation == 'lax' and converter.etree_element_class is not etree_element:
                child_tags = [converter.etree_element(e.tag, attrib=e.attrib) for e in children]
                elem = converter.etree_element(element_data.tag, text, child_tags, attrib)
            else:
                elem = converter.etree_element(element_data.tag, text, children, attrib)

            if wrong_content_type:
                reason = "wrong content type {!r}".format(type(element_data.content))
                yield self.validation_error(validation, reason, elem, **kwargs)

            if cdata_not_allowed:
                reason = "character data between child elements not allowed"
                yield self.validation_error(validation, reason, elem, **kwargs)

            for index, particle, occurs, expected in errors:
                yield self.children_validation_error(
                    validation, elem, index, particle, occurs, expected, **kwargs