Python lxml.etree 模块,XMLSchema() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用lxml.etree.XMLSchema()

项目:filtered-alert-hub    作者:filtered-alert-hub    | 项目源码 | 文件源码
def loadandvalidateCAP(capXML):

    if "urn:oasis:names:tc:emergency:cap:1.1" in capXML:
        capschema = "xsds/cap1-1.xsd"
        namespace = "urn:oasis:names:tc:emergency:cap:1.1"
    elif "urn:oasis:names:tc:emergency:cap:1.2" in capXML:
        capschema = "xsds/cap1-2.xsd"
        namespace = "urn:oasis:names:tc:emergency:cap:1.2"
    else:
        raise Exception("unknown schema: {}".format( capXML[0:100] ))

    xmlschema_doc = etree.parse(capschema)
    xmlschema = etree.XMLSchema(xmlschema_doc)  

    doc = etree.fromstring(capXML)
    if not xmlschema.validate(doc):
        raise Exception("alert not valid CAP")

    return [namespace,doc]
项目:PySIGNFe    作者:thiagopena    | 项目源码 | 文件源码
def validar(self):
        arquivo_esquema = self.caminho_esquema + self.arquivo_esquema

        # Aqui é importante remover a declaração do encoding
        # para evitar erros de conversão unicode para ascii
        xml = tira_abertura(self.xml).encode(u'utf-8')

        esquema = etree.XMLSchema(etree.parse(arquivo_esquema))

        if not esquema.validate(etree.fromstring(xml)):
            for e in esquema.error_log:
                if e.level == 1:
                    self.alertas.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', ''))
                elif e.level == 2:
                    self.erros.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', ''))

        return esquema.error_log
项目:warriorframework    作者:warriorframework    | 项目源码 | 文件源码
def xml_to_xsd_validation(file_xml, file_xsd):
        """ Verify that the XML compliance with XSD
        Arguments:
            1. file_xml: Input xml file
            2. file_xsd: xsd file which needs to be validated against xml
        Return:
            No return value
        """
        try:
            print_info("Validating:{0}".format(file_xml))
            print_info("xsd_file:{0}".format(file_xsd))
            xml_doc = parse(file_xml)
            xsd_doc = parse(file_xsd)
            xmlschema = XMLSchema(xsd_doc)
            xmlschema.assert_(xml_doc)
            return True

        except XMLSyntaxError as err:
            print_error("PARSING ERROR:{0}".format(err))
            return False

        except AssertionError, err:
            print_error("Incorrect XML schema: {0}".format(err))
            return False
项目:cfdilib    作者:Vauxoo    | 项目源码 | 文件源码
def get_documentation(self, element, namespace=None, schema_str=None):
        """**Helper method:** should return an schema specific documentation
        given an element parsing or getting the `Clark's Notation`_
        `{url:schema}Element` from the message error on validate method.

        :param str element: Element string following the Clark's Notation
        :param dict namespace: Element string following the Clark's Notation

        :returns: The documentation text if exists
        :rtype: unicode

        .. _`Clark's Notation`: http://effbot.org/zone/element-namespaces.htm
        """
        if namespace is None:
            namespace = {'xs': 'http://www.w3.org/2001/XMLSchema'}
        schema_root = etree.parse(StringIO(self.schema))
        document = schema_root.xpath(self.get_element_from_clark(element),
                                     namespaces=namespace)
        return document and document[0].text or ''
项目:supvisors    作者:julien6387    | 项目源码 | 文件源码
def parse(self, filename):
        self.parser = None
        # find parser
        try:
            from lxml.etree import parse, XMLSchema
            self.logger.info('using lxml.etree parser')
            # parse XML and validate it
            tree = parse(filename)
            # get XSD
            schemaDoc = parse(XSDContents)
            schema = XMLSchema(schemaDoc)
            if schema.validate(tree):
                self.logger.info('XML validated')
                return tree
            print >> stderr,  schema.error_log
            raise ValueError('XML NOT validated: {}'.format(filename))
        except ImportError:
            try:
                from xml.etree.ElementTree import parse
                self.logger.info('using xml.etree.ElementTree parser')
                return parse(filename)
            except ImportError:
                self.logger.critical("Failed to import ElementTree from any known place")
                raise
项目:tiss    作者:dudanogueira    | 项目源码 | 文件源码
def xsd_validate(self):

        if not self.xsd_path:
            xsd_file = 'xsd/%sV%s.xsd' % (self.arquivo_xsd, self.version.replace('.', '_'))
            self.xsd_path = os.path.join(os.path.dirname(__file__), xsd_file)
        #f = open(self.xsd_path)
        self.root_xsd = etree.parse(self.xsd_path)
        try:
            self.xsd_schema = etree.XMLSchema(self.root_xsd)
            self.xsd_valido = True
        except etree.XMLSchemaParseError as xsd_erros:
            self.xsd_valido = False
            self.xsd_erros = xsd_erros
            i = 1
            for erro in self.xsd_erros.error_log:
                self.erros['lote']['_xsd_invalido%i' % i] = "Arquivo: %s, Linha %s, Coluna: %s: %s" % (
                    erro.filename, erro.line, erro.column, erro.message
                )
                i += 1
项目:CityGML-schema-validation    作者:tudelft3d    | 项目源码 | 文件源码
def validateonefile(fIn):
    doc, xsd = getXML(fIn)
    if (doc == None) and (xsd == None):
        print "Invalid CityGML document: not a CityGML document."
        sys.exit()
    xmlschema = etree.XMLSchema(xsd)
    valid = doc.xmlschema(xsd)
    if valid == True:
        print "Document is valid."
    else:
        try:
            xmlschema.assert_(doc)
        except etree.XMLSyntaxError as e:
            print "Invalid document"
            print "Error", e
            log = xmlschema.error_log
            print log
        except AssertionError as e:
            print "INVALID DOCUMENT"
            print "================"
            print e
项目:beremiz    作者:nucleron    | 项目源码 | 文件源码
def GenerateParser(factory, xsdstring):
    ComputedClasses = factory.CreateClasses()

    if factory.FileName is not None:
        ComputedClasses = ComputedClasses[factory.FileName]
    BaseClass = [(name, XSDclass) for name, XSDclass in ComputedClasses.items() if XSDclass.IsBaseClass]

    parser = XMLClassParser(
        factory.NSMAP,
        factory.etreeNamespaceFormat,
        BaseClass[0] if len(BaseClass) == 1 else None,
        etree.XMLSchema(etree.fromstring(xsdstring)),
        strip_cdata=False, remove_blank_text=True)
    class_lookup = XMLElementClassLookUp(factory.ComputedClassesLookUp)
    parser.set_element_class_lookup(class_lookup)

    return parser
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def load(self, schema, node):
        """Load the XML Schema passed in via the node attribute.

        :type schema: zeep.xsd.schema.Schema
        :type node: etree._Element

        """
        if node is None:
            return

        if not schema.documents.has_schema_document_for_ns(self._target_namespace):
            raise RuntimeError(
                "The document needs to be registered in the schema before " +
                "it can be loaded")

        # Disable XML schema validation for now
        # if len(node) > 0:
        #     self.xml_schema = etree.XMLSchema(node)
        visitor = SchemaVisitor(schema, self)
        visitor.visit_schema(node)
项目:fomod-validator    作者:GandaG    | 项目源码 | 文件源码
def validate_tree(elem_tree, schema_file, ignore_errors=False):
    """
    Validate your FOMOD installer. Raises ValidationError if installer is not valid.
    :param elem_tree: The root element of your config xml tree.
    :param schema_file: The path to the schema file, with filename and extension.
    :param ignore_errors: If true, the function returns False instead of throwing an error.
    """
    try:
        xmlschema_doc = etree.parse(schema_file)
        xmlschema = etree.XMLSchema(xmlschema_doc)
        xmlschema.assertValid(elem_tree)
        return True
    except etree.ParseError as e:
        raise ParserError(str(e))
    except etree.DocumentInvalid as e:
        if ignore_errors:
            return False
        raise ValidationError("The Config tree is invalid with error message:\n\n" + str(e))
项目:qexsd    作者:QEF    | 项目源码 | 文件源码
def validate(self, xml_config):
        """
        Validate the configuration with XSD and with optional parameter dependencies.
        :param xml_config:
        """
        try:
            import lxml.etree as ET
        except ImportError:
            logger.debug("")
            return

        xsd = ET.parse(self._xsd_file)
        xml_schema = ET.XMLSchema(xsd)

        try:
            xml_schema.assertValid(xml_config.tostring())
        except AttributeError:
            logger.warning("XML Schema validation not available!")
        except ET.DocumentInvalid as e:
            raise XMLSchemaValidationError(e)
项目:Magic-Spoiler    作者:Cockatrice    | 项目源码 | 文件源码
def verify_xml(file, schema):
    try:
        schema_doc = etree.fromstring(schema)
    except Exception as e:
        print "XSD for " + file + " is invalid"
        print schema
        print e
        return False
    xml_schema = etree.XMLSchema(schema_doc)
    try:
        xml_doc = etree.parse(file)
    except Exception as e:
        print "XML file " + file + " is invalid"
        print e
        return False
    try:
        xml_schema.assert_(xml_doc)
    except:
        xsd_errors = xml_schema.error_log
        print "Errors validating XML file " + file + " against XSD:"
        for error in xsd_errors:
            print error
        sys.exit("Error: " + file + " does not pass Cockatrice XSD validation.")
        return False
    return True
项目:py-enarksh    作者:SetBased    | 项目源码 | 文件源码
def parse_schedule(xml, filename):
        """
        Parses a schedule definition in XML.

        :param str xml: The XML with a schedule definition
        :param str filename:

        :rtype: enarksh.xml_reader.node.ScheduleNode
        """
        with open(os.path.join(C.HOME, 'etc/enarksh.xsd'), 'rb') as f:
            xsd = f.read()

        etree.clear_error_log()
        schema_root = etree.XML(xsd)
        schema = etree.XMLSchema(schema_root)
        parser = etree.XMLParser(schema=schema, encoding='utf8')
        try:
            root = etree.fromstring(bytes(xml, 'utf8'), parser)

            # Root element must be a schedule.
            if root.tag != 'Schedule':
                raise Exception("Root element must be 'Schedule' but '{0!s}' was found.".format(root.tag))

            schedule = create_node('Schedule')
            schedule.read_xml(root)
            error = schedule.validate()
            if error:
                raise Exception(
                    "File '{0!s}' is not a valid schedule configuration file.\n{1!s}".format(filename, error))

            # Set recursion and dependency levels.
            schedule.set_levels()
        except etree.XMLSyntaxError as exception:
            log = logging.getLogger('enarksh')
            log.error(exception.error_log.filter_from_level(etree.ErrorLevels.WARNING))
            raise exception

        return schedule

    # ------------------------------------------------------------------------------------------------------------------
项目:py-enarksh    作者:SetBased    | 项目源码 | 文件源码
def parse_dynamic_worker(xml, parent):
        """
        Parses a schedule definition in XML.

        :param str xml: The XML with a schedule definition
        :param parent:

        :rtype: enarksh.xml_reader.node.CompoundJobNode
        """
        with open(os.path.join(C.HOME, 'etc/enarksh.xsd'), 'rb') as f:
            xsd = f.read()

        schema_root = etree.XML(xsd)
        schema = etree.XMLSchema(schema_root)
        parser = etree.XMLParser(schema=schema, encoding='utf8')
        root = etree.fromstring(bytes(xml, 'utf8'), parser)

        # Root element must be a dynamic inner worker.
        if root.tag != 'DynamicInnerWorker':
            raise Exception("Root element must be 'DynamicInnerWorker' but '{0!s}' was found.".format(root.tag))

        worker = create_node('DynamicInnerWorker')
        worker.read_xml(root)
        error = worker.validate(parent)
        if error:
            raise Exception("XML message is not a valid dynamic worker configuration.\n{0!s}".format(error))

        # Set recursion and dependency levels.
        worker.set_levels()

        return worker

    # ------------------------------------------------------------------------------------------------------------------
项目:py-enarksh    作者:SetBased    | 项目源码 | 文件源码
def parse_host(filename):
        """
        Parses a host definition in XML.

        :param str filename: The XML file with a host definition

        :rtype: enarksh.xml_reader.Host.Host
        """
        with open(filename, 'rt', encoding='utf-8') as stream:
            xml = stream.read()

        with open(os.path.join(C.HOME, 'etc/enarksh.xsd'), 'rb') as stream:
            xsd = stream.read()

        schema_root = etree.XML(xsd)
        schema = etree.XMLSchema(schema_root)
        parser = etree.XMLParser(schema=schema, encoding='utf8')
        root = etree.fromstring(bytes(xml, 'utf8'), parser)

        # Root element must be a schedule.
        if root.tag != 'Host':
            raise Exception("Root element must be 'Host' but '{0!s}' was found.".format(root.tag))

        host = Host()
        host.read_xml(root)
        error = host.validate()
        if error:
            raise Exception("File '{0!s}' is not a valid host configuration file.\n{1!s}".format(filename, error))

        return host

# ----------------------------------------------------------------------------------------------------------------------
项目:geocoder-ie    作者:devgateway    | 项目源码 | 文件源码
def is_valid_schema(xml_path, version='202'):
    xsd_path = get_activities_xsd_file_path(version)
    xmlschema_doc = etree.parse(xsd_path)
    xmlschema = etree.XMLSchema(xmlschema_doc)

    xml_doc = etree.parse(xml_path)

    return xmlschema.validate(xml_doc)
项目:python-sepadd    作者:raphaelm    | 项目源码 | 文件源码
def validate_xml(xmlout, schema):
    with open(os.path.join(os.path.dirname(__file__), schema + '.xsd'), 'rb') as schema_file:
        schema_xml = schema_file.read()
    schema_root = etree.XML(schema_xml)
    schema = etree.XMLSchema(schema_root)
    parser = etree.XMLParser(schema=schema)
    xml_root = etree.fromstring(xmlout, parser)
    return etree.tostring(xml_root, pretty_print=True)
项目:cfdilib    作者:Vauxoo    | 项目源码 | 文件源码
def validate(self, schema_str, xml_valid):
        """Compare the valid information on an xml from  given schema.

        :param str schema_str: content string from schema file.
        :param str xml_valid: content string from xml file.
        :returns: If it is Valid or Not.
        :rtype: bool
        """
        # TODO: be able to get doc for error given an xsd.
        # Changed path to allow have xsd that are imported by others xsd in the
        # same library, and not call to SAT page each time that is generated
        # a new XML.
        with change_path():
            path = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'templates')
            os.chdir(path)
            schema_root = etree.parse(StringIO(schema_str))
            schema = etree.XMLSchema(schema_root)
        try:
            tree = etree.parse(StringIO(xml_valid.encode('UTF-8')))
            schema.assertValid(tree)
        except etree.DocumentInvalid as ups:
            self.ups = ups
        finally:
            if self.ups:
                self.valid = False
            else:
                self.valid = True
            return self.valid
项目:dati-ckan-docker    作者:italia    | 项目源码 | 文件源码
def _is_valid(cls, xml, xsd_filepath, xsd_name):
        '''Returns whether or not an XML file is valid according to
        an XSD. Returns a tuple, the first value is a boolean indicating
        whether the validation passed or not. The second is a list of tuples,
        each containing the error message and the error line.

        Params:
          xml - etree of the XML to be validated
          xsd_filepath - full path to the XSD file
          xsd_name - string describing the XSD

        Returns:
          (is_valid, [(error_message_string, error_line_number)])
        '''
        xsd = etree.parse(xsd_filepath)
        schema = etree.XMLSchema(xsd)
        # With libxml2 versions before 2.9, this fails with this error:
        #    gmx_schema = etree.XMLSchema(gmx_xsd)
        # File "xmlschema.pxi", line 103, in
        # lxml.etree.XMLSchema.__init__ (src/lxml/lxml.etree.c:116069)
        # XMLSchemaParseError: local list type: A type, derived by list or
        # union, must have the simple ur-type definition as base type,
        # not '{http://www.opengis.net/gml/3.2}doubleList'., line 118
        try:
            schema.assertValid(xml)
        except etree.DocumentInvalid:
            log.info(
                'Validation errors found using schema {0}'.format(xsd_name))
            errors = []
            for error in schema.error_log:
                errors.append((error.message, error.line))
            errors.insert
            return False, errors
        return True, []
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def validate(self):
            import urllib2
            schema_src_file = urllib2.urlopen(self.schema_url)
            schema_doc = etree.parse(schema_src_file)
            schema = etree.XMLSchema(schema_doc)
            doc = etree.fromstring(self.get_as_xml())
            schema.assertValid(doc)
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def schedule_schema():
    from lxml import etree
    with open('tests/functional/fixtures/schedule.xsd', 'r') as xsd:
        source = xsd.read()
    schema = etree.XML(source)
    return etree.XMLSchema(schema)
项目:honeyd-python    作者:sookyp    | 项目源码 | 文件源码
def validate_template(self, xml_file, xsd_file):
        """Function check the validity of the XML configuration
        Args:
            xml_file : network configuration file
            xsd_file : Schema Definition defining the ruleset
        """
        xml_schema = etree.parse(xsd_file)
        xsd = etree.XMLSchema(xml_schema)
        xml = etree.parse(xml_file)
        xsd.validate(xml)
        if xsd.error_log:
            logger.error('Error: Problem with parsing configuration template: %s', xsd.error_log)
            sys.exit(1)
项目:aiida-fleur    作者:broeder-j    | 项目源码 | 文件源码
def _set_inp_dict(self):
        """
        Sets the inputxml_dict from the inp.xml file attached to FleurinpData

        1. get inp.xml strucutre/layout
        2. load inp.xml file
        3. call inpxml_to_dict
        4. set inputxml_dict
        """
        from aiida_fleur.tools.xml_util import get_inpxml_file_structure, inpxml_todict
        # get inpxml structure
        inpxmlstructure = get_inpxml_file_structure()

        # read xmlinp file into an etree with autocomplition from schema
        inpxmlfile = self.get_file_abs_path('inp.xml')

        xmlschema_doc = etree.parse(self._schema_file_path)
        xmlschema = etree.XMLSchema(xmlschema_doc)
        parser = etree.XMLParser(schema=xmlschema, attribute_defaults=True)
        #dtd_validation=True

        tree = etree.parse(inpxmlfile)#, parser)
        # there is a bug when validating at parsetime, therefore we only
        #validate at parse time if file is invalid, to get nice error message
        if not xmlschema.validate(tree):
            tree = etree.parse(inpxmlfile, parser)

        root = tree.getroot()

        # convert etree into python dictionary
        inpxml_dict = inpxml_todict(root, inpxmlstructure)

        # set inpxml_dict attribute
        self._set_attr('inp_dict', inpxml_dict)


    # tracing user changes
项目:aiida-fleur    作者:broeder-j    | 项目源码 | 文件源码
def get_tag(self, xpath):
        """
        Tries to evalutate an xpath expression. If it fails it logs it.

        :param root node of an etree and an xpath expression (relative, or absolute)
        :returns ALWAYS a node list
        """
        from lxml import etree

        if 'inp.xml' in self.files:
            # read in inpxml
            inpxmlfile = self.get_file_abs_path('inp.xml')

            if self._schema_file_path: # Schema there, parse with schema
                #xmlschema_doc = etree.parse(self._schema_file_path)
                #xmlschema = etree.XMLSchema(xmlschema_doc)
                #parser = etree.XMLParser(schema=xmlschema, attribute_defaults=True)
                tree = etree.parse(inpxmlfile)#, parser)
            else: #schema not there, parse without
                print 'parsing inp.xml without XMLSchema'
                tree = etree.parse(inpxmlfile)

            root = tree.getroot()
        else:
            raise InputValidationError(
                      "No inp.xml file yet specified, to get a tag from")

        try:
            return_value = root.xpath(xpath)
        except etree.XPathEvalError:
            #print (
            raise InputValidationError(
                'There was a XpathEvalError on the xpath: {} \n Either it does '
                'not exist, or something is wrong with the expression.'
                ''.format(xpath))
            return []
        if len(return_value) == 1:
            return return_value
        else:
            return return_value
项目:lcp-testing-tools    作者:edrlab    | 项目源码 | 文件源码
def test_validate_encryption_xml(self):
        """
        Check if encryption.xml is present in the protected publication
        Validate the xml file.
        """

        target_path = os.path.join(self.config_manager.working_path, os.path.basename(self.file_path).replace('.','-'))
        try:
            with zipfile.ZipFile(self.file_path) as zip:
                # it will store the xml file in the working dir, in a subfolder named after the protected publication
                encryption_file = zip.extract('META-INF/encryption.xml', target_path)
        except KeyError as err:
            raise TestSuiteRunningError(err)

        """
        The W3C schema checks the following rules:
        * In each EncryptedData element:
        - The encryption method must be (aes256-cbc) (LCP profile basic and 1.0)     
        - The ds:KeyInfo element MUST point to the Content Key using the ds:RetrievalMethod element.
        - The URI attribute of ds:RetrievalMethod MUST use a value of “license.lcpl#/encryption/content_key” to point to the encrypted Content Key stored in the License Document. 
        - The Type attribute MUST use a value of “http://readium.org/2014/01/lcp#EncryptedContentKey” to identify the target of the URI as an encrypted Content Key.
        """
        schema = etree.parse('schema/encryption.xsd')
        xsd = etree.XMLSchema(schema)

        doc = etree.parse(os.path.join(target_path, 'META-INF/encryption.xml'))
        if not xsd.validate(doc):
            for error in xsd.error_log:
                print (error.message, error.line, error.column)
            raise TestSuiteRunningError("encryption.xml is invalid")
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def validate(self):
            import urllib2
            schema_src_file = urllib2.urlopen(self.schema_url)
            schema_doc = etree.parse(schema_src_file)
            schema = etree.XMLSchema(schema_doc)
            doc = etree.fromstring(self.get_as_xml())
            schema.assertValid(doc)
项目:ryu-lagopus-ext    作者:lagopus    | 项目源码 | 文件源码
def validate(tree):
    schema = ET.XMLSchema(file=of_config.OF_CONFIG_1_1_1_XSD)
    if not schema(tree):
        print(schema.error_log)
项目:rotest    作者:gregoil    | 项目源码 | 文件源码
def __init__(self):
        super(XMLParser, self).__init__()
        self.scheme = etree.XMLSchema(file=self._SCHEME_PATH)

        self.complex_decoders = {
                         self._LIST_TYPE: self._decode_list,
                         self._DICT_TYPE: self._decode_dict,
                         self._CLASS_TYPE: self._decode_class,
                         self._RESOURCE_TYPE: self._decode_resource,
                         self._RESOURCE_DATA_TYPE: self._decode_resource_data}
项目:pyIPXACT    作者:Paebbels    | 项目源码 | 文件源码
def ToXml(self):
        buffer = dedent("""\
            <?xml version="1.0" encoding="UTF-8"?>
            <{xmlns}:catalog
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:{xmlns}="{schemaUri}"
                xsi:schemaLocation="{schemaUri} {schemaUrl}">
            {versionedIdentifier}
                <{xmlns}:description>{description}</{xmlns}:description>
            """).format(
                xmlns=__DEFAULT_SCHEMA__.NamespacePrefix,
                schemaUri=__DEFAULT_SCHEMA__.SchemaUri,
                schemaUrl=__DEFAULT_SCHEMA__.SchemaUrl,
                versionedIdentifier=self._vlnv.ToXml(isVersionedIdentifier=True),
                description=self._description
            )

        if self._catalogs:
            buffer += "\t<{xmlns}:catalogs>\n"
            for ipxactFile in self._catalogs:
                buffer += ipxactFile.ToXml(2)
            buffer += "\t</{xmlns}:catalogs>\n"

        if self._components:
            buffer += "\t<{xmlns}:components>\n"
            for ipxactFile in self._components:
                buffer += ipxactFile.ToXml(2)
            buffer += "\t</{xmlns}:components>\n"

        buffer += dedent("""\
            </{xmlns}:catalog>
            """)

        return buffer.format(xmlns=__DEFAULT_SCHEMA__.NamespacePrefix)
项目:graphit-tool    作者:mklemm2    | 项目源码 | 文件源码
def __init__(self, xsdfile):
        xml_schema_doc = et.parse(xsdfile)
        self.xml_schema = et.XMLSchema(xml_schema_doc)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_default_types():
    schema = xsd.Schema()
    xsd_string = schema.get_type('{http://www.w3.org/2001/XMLSchema}string')
    assert xsd_string == xsd.String()
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_default_types_not_found():
    schema = xsd.Schema()
    with pytest.raises(exceptions.LookupError):
        schema.get_type('{http://www.w3.org/2001/XMLSchema}bar')
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_default_elements():
    schema = xsd.Schema()
    xsd_schema = schema.get_element('{http://www.w3.org/2001/XMLSchema}schema')
    isinstance(xsd_schema, Schema)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_default_elements_not_found():
    schema = xsd.Schema()
    with pytest.raises(exceptions.LookupError):
        schema.get_element('{http://www.w3.org/2001/XMLSchema}bar')
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_invalid_localname_handling():
    schema = xsd.Schema(load_xml("""
        <?xml version="1.0"?>
        <xs:schema
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/"
            targetNamespace="http://tests.python-zeep.org/"
            elementFormDefault="qualified">
        </xs:schema>
    """))

    qname = '{http://tests.python-zeep.org/}foo'
    namespace = 'http://tests.python-zeep.org/'
    localname = 'foo'

    with pytest.raises(exceptions.LookupError) as exc:
        schema.get_element(qname)
    assert namespace in str(exc.value.message)
    assert localname in str(exc.value.message)

    with pytest.raises(exceptions.LookupError) as exc:
        schema.get_type(qname)
    assert namespace in str(exc.value.message)
    assert localname in str(exc.value.message)

    with pytest.raises(exceptions.LookupError) as exc:
        schema.get_group(qname)
    assert namespace in str(exc.value.message)
    assert localname in str(exc.value.message)

    with pytest.raises(exceptions.LookupError) as exc:
        schema.get_attribute(qname)
    assert namespace in str(exc.value.message)
    assert localname in str(exc.value.message)

    with pytest.raises(exceptions.LookupError) as exc:
        schema.get_attribute_group(qname)
    assert namespace in str(exc.value.message)
    assert localname in str(exc.value.message)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_schema_doc_repr_val():
    schema = xsd.Schema(load_xml("""
        <?xml version="1.0"?>
        <xs:schema
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/"
            targetNamespace="http://tests.python-zeep.org/"
            elementFormDefault="qualified">
        </xs:schema>
    """))
    docs = schema._get_schema_documents('http://tests.python-zeep.org/')
    assert len(docs) == 1
    doc = docs[0]
    assert repr(doc) == "<SchemaDocument(location=None, tns='http://tests.python-zeep.org/', is_empty=True)>"
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_get_type_through_import():
    schema_a = etree.fromstring("""
        <?xml version="1.0"?>
        <xs:schema
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/a"
            targetNamespace="http://tests.python-zeep.org/a"
            xmlns:b="http://tests.python-zeep.org/b"
            elementFormDefault="qualified">

            <xs:import
                schemaLocation="http://tests.python-zeep.org/b.xsd"
                namespace="http://tests.python-zeep.org/b"/>
            <xs:element name="foo" type="b:bar"/>

        </xs:schema>
    """.strip())

    schema_b = etree.fromstring("""
        <?xml version="1.0"?>
        <xs:schema
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/b"
            targetNamespace="http://tests.python-zeep.org/b"
            xmlns:c="http://tests.python-zeep.org/c"
            elementFormDefault="qualified">

            <xs:complexType name="bar"/>

        </xs:schema>
    """.strip())

    transport = DummyTransport()
    transport.bind('http://tests.python-zeep.org/a.xsd', schema_a)
    transport.bind('http://tests.python-zeep.org/b.xsd', schema_b)
    xsd.Schema(schema_a, transport=transport)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_multiple_no_namespace():
    node_a = etree.fromstring("""
        <?xml version="1.0"?>
        <xsd:schema
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/a"
            targetNamespace="http://tests.python-zeep.org/a"
            elementFormDefault="qualified">

          <xsd:import schemaLocation="http://tests.python-zeep.org/b.xsd"/>
          <xsd:import schemaLocation="http://tests.python-zeep.org/c.xsd"/>
        </xsd:schema>
    """.strip())

    node_b = etree.fromstring("""
        <?xml version="1.0"?>
        <xsd:schema
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            elementFormDefault="qualified">
        </xsd:schema>
    """.strip())

    transport = DummyTransport()
    transport.bind('http://tests.python-zeep.org/b.xsd', node_b)
    transport.bind('http://tests.python-zeep.org/c.xsd', node_b)
    xsd.Schema(node_a, transport=transport)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_multiple_only_target_ns():
    node_a = etree.fromstring("""
        <?xml version="1.0"?>
        <xsd:schema
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/a"
            targetNamespace="http://tests.python-zeep.org/a"
            elementFormDefault="qualified">

          <xsd:import schemaLocation="http://tests.python-zeep.org/b.xsd"/>
          <xsd:import schemaLocation="http://tests.python-zeep.org/c.xsd"/>
        </xsd:schema>
    """.strip())

    node_b = etree.fromstring("""
        <?xml version="1.0"?>
        <xsd:schema
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            elementFormDefault="qualified"
            targetNamespace="http://tests.python-zeep.org/duplicate-ns">
        </xsd:schema>
    """.strip())

    transport = DummyTransport()
    transport.bind('http://tests.python-zeep.org/b.xsd', node_b)
    transport.bind('http://tests.python-zeep.org/c.xsd', node_b)
    xsd.Schema(node_a, transport=transport)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_schema_import_xmlsoap():
    node_a = etree.fromstring("""
        <?xml version="1.0"?>
        <xsd:schema
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/a"
            targetNamespace="http://tests.python-zeep.org/a"
            xmlns:b="http://tests.python-zeep.org/b"
            elementFormDefault="qualified">
          <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
        </xsd:schema>
    """.strip())
    transport = DummyTransport()
    xsd.Schema(node_a, transport=transport)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_schema_import_unresolved():
    node_a = etree.fromstring("""
        <?xml version="1.0"?>
        <xsd:schema
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/a"
            targetNamespace="http://tests.python-zeep.org/a"
            xmlns:b="http://tests.python-zeep.org/b"
            elementFormDefault="qualified">
          <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
        </xsd:schema>
    """.strip())
    transport = DummyTransport()
    xsd.Schema(node_a, transport=transport)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_no_target_namespace():
    node_a = etree.fromstring("""
        <?xml version="1.0"?>
        <xsd:schema
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/a"
            targetNamespace="http://tests.python-zeep.org/a"
            elementFormDefault="qualified">

          <xsd:import schemaLocation="http://tests.python-zeep.org/b.xsd"/>

          <xsd:element name="container">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element ref="bla"/>
              </xsd:sequence>
            </xsd:complexType>
          </xsd:element>

        </xsd:schema>
    """.strip())

    node_b = etree.fromstring("""
        <?xml version="1.0"?>
        <xsd:schema
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            elementFormDefault="qualified">
            <xsd:element name="bla" type="xsd:string"/>
        </xsd:schema>
    """.strip())

    transport = DummyTransport()
    transport.bind('http://tests.python-zeep.org/b.xsd', node_b)
    xsd.Schema(node_a, transport=transport)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_include_relative():
    node_a = etree.fromstring("""
        <?xml version="1.0"?>
        <xs:schema
            xmlns="http://tests.python-zeep.org/tns"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://tests.python-zeep.org/a"
            elementFormDefault="qualified">

            <xs:include schemaLocation="http://tests.python-zeep.org/subdir/b.xsd"/>

        </xs:schema>
    """.strip())

    node_b = etree.fromstring("""
        <?xml version="1.0"?>
        <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
            <xs:include schemaLocation="c.xsd"/>
            <xs:element name="bar" type="xs:string"/>
        </xs:schema>
    """.strip())

    node_c = etree.fromstring("""
        <?xml version="1.0"?>
        <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
            <xs:element name="foo" type="xs:string"/>
        </xs:schema>
    """.strip())

    transport = DummyTransport()
    transport.bind('http://tests.python-zeep.org/subdir/b.xsd', node_b)
    transport.bind('http://tests.python-zeep.org/subdir/c.xsd', node_c)

    schema = xsd.Schema(node_a, transport=transport)
    schema.get_element('{http://tests.python-zeep.org/a}foo')
    schema.get_element('{http://tests.python-zeep.org/a}bar')
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_merge():
    node_a = etree.fromstring("""
        <?xml version="1.0"?>
        <xs:schema
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/a"
            targetNamespace="http://tests.python-zeep.org/a"
            xmlns:b="http://tests.python-zeep.org/b"
            elementFormDefault="qualified">
          <xs:element name="foo" type="xs:string"/>
        </xs:schema>
    """.strip())

    node_b = etree.fromstring("""
        <?xml version="1.0"?>
        <xs:schema
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/b"
            targetNamespace="http://tests.python-zeep.org/b"
            elementFormDefault="qualified">
          <xs:element name="foo" type="xs:int"/>
        </xs:schema>
    """.strip())

    schema_a = xsd.Schema(node_a)
    schema_b = xsd.Schema(node_b)
    schema_a.merge(schema_b)

    schema_a.get_element('{http://tests.python-zeep.org/a}foo')
    schema_a.get_element('{http://tests.python-zeep.org/b}foo')
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def test_xml_namespace():
    xmlns = load_xml("""
        <?xml version="1.0"?>
        <xs:schema
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:xml="http://www.w3.org/XML/1998/namespace"
            targetNamespace="http://www.w3.org/XML/1998/namespace"
            elementFormDefault="qualified">
          <xs:attribute name="lang" type="xs:string"/>
        </xs:schema>
    """)

    transport = DummyTransport()
    transport.bind('http://www.w3.org/2001/xml.xsd', xmlns)

    xsd.Schema(load_xml("""
        <?xml version="1.0"?>
        <xs:schema
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://tests.python-zeep.org/"
            targetNamespace="http://tests.python-zeep.org/"
            elementFormDefault="qualified">
          <xs:import namespace="http://www.w3.org/XML/1998/namespace"
                     schemaLocation="http://www.w3.org/2001/xml.xsd"/>
          <xs:element name="container">
            <xs:complexType>
              <xs:sequence/>
              <xs:attribute ref="xml:lang"/>
            </xs:complexType>
          </xs:element>
        </xs:schema>
    """), transport=transport)
项目:python-zeep    作者:mvantellingen    | 项目源码 | 文件源码
def _create_prefix_map(self):
        prefix_map = {
            'xsd': 'http://www.w3.org/2001/XMLSchema',
        }
        i = 0
        for namespace in self.documents.get_all_namespaces():
            if namespace is None or namespace in prefix_map.values():
                continue

            prefix_map['ns%d' % i] = namespace
            i += 1
        return prefix_map
项目:geos    作者:grst    | 项目源码 | 文件源码
def test_initialize_schema(self):
        """Tests the creation Schema instance"""
        schema = Schema("ogckml22.xsd")
        self.assertTrue(isinstance(schema.schema, etree.XMLSchema))
项目:geos    作者:grst    | 项目源码 | 文件源码
def __init__(self, schema):
        module_dir = os.path.split(__file__)[0]   # get the module path
        schema_file = os.path.join(module_dir, "schemas", schema)
        with open(schema_file) as f:
            self.schema = etree.XMLSchema(file=f)
项目:alfred-ec2    作者:SoMuchToGrok    | 项目源码 | 文件源码
def validate(self):
            import urllib2
            schema_src_file = urllib2.urlopen(self.schema_url)
            schema_doc = etree.parse(schema_src_file)
            schema = etree.XMLSchema(schema_doc)
            doc = etree.fromstring(self.get_as_xml())
            schema.assertValid(doc)
项目:pygcam    作者:JGCRI    | 项目源码 | 文件源码
def validate(self, raiseOnError=True):
        """
        Validate a ParameterList against ``self.schemaFile``. Optionally raises an
        error on failure, else return boolean validity status. If no schema file
        is defined, return ``True``.
        """
        if not self.schemaPath:
            return True

        tree = self.tree

        # ensure that the entire directory has been extracted so that 'xs:include' works
        pkg.resource_filename('pygcam', os.path.dirname(self.schemaPath))
        abspath = pkg.resource_filename('pygcam', self.schemaPath)

        xsd = ET.parse(abspath)
        schema = ET.XMLSchema(xsd)

        if raiseOnError:
            try:
                schema.assertValid(tree)
                return True
            except ET.DocumentInvalid as e:
                raise XmlFormatError("Validation of '%s'\n  using schema '%s' failed:\n  %s" % (self.filename, self.schemaPath, e))
        else:
            valid = schema.validate(tree)
            return valid