use the (included) jing library to validate the XML.
540427
def jing(self, tag=None, schemas=None, schemafn=None, ext='.rnc'):
        """"""
        from . import JARS

        java = os.environ.get('java') or 'java'
        jingfn = os.path.join(JARS, 'jing.jar')
        tag = tag or self.root.tag
        schemas = schemas or self.schemas
        schemafn = schemafn or Schema.filename(tag, schemas, ext=ext)
        if schemafn is not None:
            cmd = [java, '-jar', jingfn, '-c', schemafn]
            if os.path.splitext(schemafn)[-1].lower() != '.rnc':
                cmd.pop(cmd.index('-c'))
            try:
                fn = self.fn
                if fn is None or not os.path.exists(fn):
                    tempf = tempfile.NamedTemporaryFile()
                    fn = tempf.name
                    tempf.close()
                    open(fn, 'wb').write(etree.tounicode(self.root).encode('utf-8'))
                subprocess.check_output(cmd + [fn])
            except subprocess.CalledProcessError as e:
                tbtext = html.unescape(str(e.output, 'UTF-8'))
                raise RuntimeError(tbtext).with_traceback(sys.exc_info()[2]) from None
521802
private function validateXml() : void
    {
        if (!isset($this->xml->project) || !isset($this->xml->project->metrics)) {
            throw new RuntimeException('invalid clover xml file');
        }
    }
802309
private void validateXmlTree(Node received, Node source, 
            XmlMessageValidationContext validationContext, NamespaceContext namespaceContext, TestContext context) {
        switch(received.getNodeType()) {
            case Node.DOCUMENT_TYPE_NODE:
                doDocumentTypeDefinition(received, source, validationContext, namespaceContext, context);
                break;
            case Node.DOCUMENT_NODE:
                validateXmlTree(received.getFirstChild(), source.getFirstChild(),
                        validationContext, namespaceContext, context);
                break;
            case Node.ELEMENT_NODE:
                doElement(received, source, validationContext, namespaceContext, context);
                break;
            case Node.ATTRIBUTE_NODE:
                throw new IllegalStateException();
            case Node.COMMENT_NODE:
                validateXmlTree(received.getNextSibling(), source,
                        validationContext, namespaceContext, context);
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                doPI(received);
                break;
        }
    }
103276
def validate(ctx, schema, all_schemata):
    """"""

    database = ctx.obj['db']

    if schema is None:
        if all_schemata is False:
            log('No schema given. Read the help', lvl=warn)
            return
        else:
            schemata = database.objectmodels.keys()
    else:
        schemata = [schema]

    for schema in schemata:
        try:
            things = database.objectmodels[schema]
            with click.progressbar(things.find(), length=things.count(),
                                   label='Validating %15s' % schema) as object_bar:
                for obj in object_bar:
                    obj.validate()
        except Exception as e:

            log('Exception while validating:',
                schema, e, type(e),
                '\n\nFix this object and rerun validation!',
                emitter='MANAGE', lvl=error)

    log('Done')
130472
private function validateDtd()
    {
        $libxmlUseInternalErrors = libxml_use_internal_errors(true);
        $dom = $this->writeXml();

        $secureDtdEntityResolver = new SecureDtdEntityResolver();
        $dtd = $secureDtdEntityResolver->resolveEntity($dom->doctype);


        $systemId = 'data://text/plain;base64,'.base64_encode($dtd);

        $creator = new DOMImplementation;
        $doctype = $creator->createDocumentType(
            static::DOCUMENT_TYPE_QUALIFIED_NAME,
            static::DOCUMENT_TYPE_PUBLIC_ID,
            $systemId
        );
        $new = $creator->createDocument('', '', $doctype);

        $oldNode = $dom->getElementsByTagName(static::DOCUMENT_TYPE_QUALIFIED_NAME)->item(0);
        $newNode = $new->importNode($oldNode, true);
        $new->appendChild($newNode);

        if (!$new->validate()) {
            /** @var LibXMLError[] $errors */
            $errors = libxml_get_errors();
            $errMsgStack = [];
            foreach ($errors as $error) {
                $errMsgStack[] = $error->message;
            }
            $errMsg = implode(" \n", $errMsgStack);

            libxml_use_internal_errors($libxmlUseInternalErrors);
            throw new InvalidDtdSchemaException($errMsg);
        }
        libxml_use_internal_errors($libxmlUseInternalErrors);
    }
713012
protected void validate() {
    // make sure that the source uri is set correctly.
    if (mSourceUri == null) {
      throw new BuilderException("Source must be set!");
    }

    // For local resource we require caller to specify statically generated resource id as a path.
    if (UriUtil.isLocalResourceUri(mSourceUri)) {
      if (!mSourceUri.isAbsolute()) {
        throw new BuilderException("Resource URI path must be absolute.");
      }
      if (mSourceUri.getPath().isEmpty()) {
        throw new BuilderException("Resource URI must not be empty");
      }
      try {
        Integer.parseInt(mSourceUri.getPath().substring(1));
      } catch (NumberFormatException ignored) {
        throw new BuilderException("Resource URI path must be a resource id.");
      }
    }

    // For local asset we require caller to specify absolute path of an asset, which will be
    // resolved by AssetManager relative to configured asset folder of an app.
    if (UriUtil.isLocalAssetUri(mSourceUri) && !mSourceUri.isAbsolute()) {
      throw new BuilderException("Asset URI path must be absolute.");
    }
  }
449895
def validatePopElement(self, doc, elem, qname):
        
        if doc is None: doc__o = None
        else: doc__o = doc._o
        if elem is None: elem__o = None
        else: elem__o = elem._o
        ret = libxml2mod.xmlValidatePopElement(self._o, doc__o, elem__o, qname)
        return ret
934654
def validate():
    ''''''
    with current_app.test_request_context():
        schema = json.loads(json.dumps(api.__schema__))
    try:
        schemas.validate(schema)
        success('API specifications are valid')
    except schemas.SchemaValidationError as e:
        exit_with_error('API specifications are not valid', e)
1269264
public static void validateXml(Node doc, InputStream schemaStream)
 throws AlipayApiException {
        try {
            Source source = new StreamSource(schemaStream);
            Schema schema = SchemaFactory.newInstance(
                    XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source);

            Validator validator = schema.newValidator();
            validator.validate(new DOMSource(doc));
        } catch (SAXException e) {
            throw new AlipayApiException("XML_VALIDATE_ERROR", e);
        } catch (IOException e) {
            throw new AlipayApiException("XML_READ_ERROR", e);
        } finally {
            if (schemaStream != null) {
                try {
                    schemaStream.close();
                } catch (IOException e) {
                    // nothing to do
                }
            }
        }
    }
725507
protected void validateXMLSchema(Message receivedMessage, XmlMessageValidationContext validationContext) {
        if (receivedMessage.getPayload() == null || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {
            return;
        }

        try {
            Document doc = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));

            if (!StringUtils.hasText(doc.getFirstChild().getNamespaceURI())) {
                return;
            }

            log.debug("Starting XML schema validation ...");

            XmlValidator validator = null;
            XsdSchemaRepository schemaRepository = null;
            if (validationContext.getSchema() != null) {
                validator = applicationContext.getBean(validationContext.getSchema(), XsdSchema.class).createValidator();
            } else if (validationContext.getSchemaRepository() != null) {
                schemaRepository = applicationContext.getBean(validationContext.getSchemaRepository(), XsdSchemaRepository.class);
            } else if (schemaRepositories.size() == 1) {
                schemaRepository = schemaRepositories.get(0);
            } else if (schemaRepositories.size() > 0) {
                for (XsdSchemaRepository repository : schemaRepositories) {
                    if (repository.canValidate(doc)) {
                        schemaRepository = repository;
                    }
                }
                
                if (schemaRepository == null) {
                    throw new CitrusRuntimeException(String.format("Failed to find proper schema repository in Spring bean context for validating element '%s(%s)'",
                            doc.getFirstChild().getLocalName(), doc.getFirstChild().getNamespaceURI()));
                }
            } else {
                log.warn("Neither schema instance nor schema repository defined - skipping XML schema validation");
                return;
            }
            
            if (schemaRepository != null) {
                if (!schemaRepository.canValidate(doc)) {
                    throw new CitrusRuntimeException(String.format("Unable to find proper XML schema definition for element '%s(%s)' in schema repository '%s'",
                            doc.getFirstChild().getLocalName(),
                            doc.getFirstChild().getNamespaceURI(),
                            schemaRepository.getName()));
                }

                List<Resource> schemas = new ArrayList<>();
                for (XsdSchema xsdSchema : schemaRepository.getSchemas()) {
                    if (xsdSchema instanceof XsdSchemaCollection) {
                        for (Resource resource : ((XsdSchemaCollection) xsdSchema).getSchemaResources()) {
                            schemas.add(resource);
                        }                            
                    } else if (xsdSchema instanceof WsdlXsdSchema) {
                        for (Resource resource : ((WsdlXsdSchema) xsdSchema).getSchemaResources()) {
                            schemas.add(resource);
                        }
                    } else {
                        synchronized (transformerFactory) {
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            try {
                                transformerFactory.newTransformer().transform(xsdSchema.getSource(), new StreamResult(bos));
                            } catch (TransformerException e) {
                                throw new CitrusRuntimeException("Failed to read schema " + xsdSchema.getTargetNamespace(), e);
                            }
                            schemas.add(new ByteArrayResource(bos.toByteArray()));
                        }
                    }
                }
                
                validator = XmlValidatorFactory.createValidator(schemas.toArray(new Resource[schemas.size()]), WsdlXsdSchema.W3C_XML_SCHEMA_NS_URI);
            }
            
            SAXParseException[] results = validator.validate(new DOMSource(doc));
            if (results.length == 0) {
                log.info("XML schema validation successful: All values OK");
            } else {
                log.error("XML schema validation failed for message:\n" +
                        XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));
                
                // Report all parsing errors
                log.debug("Found " + results.length + " schema validation errors");
                StringBuilder errors = new StringBuilder();
                for (SAXParseException e : results) {
                    errors.append(e.toString());
                    errors.append("\n");
                }
                log.debug(errors.toString());

                throw new ValidationException("XML schema validation failed:", results[0]);
            }
        } catch (IOException e) {
            throw new CitrusRuntimeException(e);
        }
    }
1034642
public void validate() {
    Validator validator = this.schema.newValidator();
    InputStream in = null;
    try {
      if(this.xmlFile != null) {
        in = this.xmlFile.openStream();
      } else {
        // TODO: check if we need to specify the encoding
        in = new ByteArrayInputStream(this.serializedRule.getBytes()) ;
      }
      validator.validate(new StreamSource(in));
    } catch (SAXException e) {
      throw new RulesException("Rules file does not conform to the schema", e);
    } catch (IOException e) {
      if(this.xmlFile != null) {
        throw new RulesException("Could not read file " + this.xmlFile, e);
      } else {
        throw new RulesException("Could not read serialized rule " + this.serializedRule, e);
      }
        
    } finally {
      Closeables.closeQuietly(in);
    }
  }
75495
def validate(document, schema, log_qualifier = True):
    
    if isinstance(schema, ValidatorNode):
        if not validate(document, schema.content):
            return False
        if not schema.validator(document, schema.content):
            if log_qualifier:
                LOG.error("%r failed to validate with qualifier %s", document, schema.validator.__name__)
            return False
        return True
    elif isinstance(schema, dict):
        if not isinstance(document, dict):
            LOG.error("wanted a dictionary, got a %s", document.__class__.__name__)
            return False
        generic = []
        optional = {}
        optionalnull = {}
        mandatory = []
        for key, schema_val in schema.iteritems():
            if isinstance(key, ValidatorNode):
                if key.mode == 'mandatory':
                    mandatory.append((key, schema_val))
                else:
                    generic.append((key, schema_val))
            elif isinstance(schema_val, Optional):
                optional[key] = schema_val
            elif isinstance(schema_val, OptionalNull):
                optional[key] = schema_val
                optionalnull[key] = True
            else:
                mandatory.append((key, schema_val))

        doc_copy = document.copy()

        for key, schema_val in mandatory:
            if isinstance(key, ValidatorNode):
                nb = 0
                rm = []
                for doc_key, doc_val in doc_copy.iteritems():
                    if not validate(doc_key, key, False):
                        continue

                    nb += 1

                    if validate(doc_val, schema_val):
                        rm.append(doc_key)
                    else:
                        return False

                if nb == 0:
                    LOG.error("missing document %r for qualifier: %r", key.content, key.validator.__name__)
                    return False
                elif key.min is not None and nb < key.min:
                    LOG.error("no enough document %r for qualifier: %r (min: %r, found: %r)", key.content, key.validator.__name__, key.min, nb)
                    return False
                elif key.max is not None and nb > key.max:
                    LOG.error("too many document %r for qualifier: %r (max: %r, found: %r)", key.content, key.validator.__name__, key.max, nb)
                    return False
                else:
                    for x in rm:
                        del doc_copy[x]
                    continue

            doc_val = doc_copy.get(key, Nothing)
            if doc_val is Nothing:
                LOG.error("missing key %r in document", key)
                return False

            if helpers.is_scalar(schema_val):
                if not validate(doc_val, schema_val):
                    return False
                del doc_copy[key]
                continue

            if schema_val.modifier:
                for modname in schema_val.modifier:
                    if modname in _modifiers:
                        document[key] = _modifiers[modname](document[key])
                        doc_val = _modifiers[modname](doc_val)
                    elif hasattr(doc_val, modname):
                        document[key] = getattr(document[key], modname)()
                        doc_val = getattr(doc_val, modname)()

            if _valid_len(key, doc_val, schema_val.min_len, schema_val.max_len) is False:
                return False
            if not validate(doc_val, schema_val.content):
                return False
            del doc_copy[key]

        for key, schema_val in generic:
            nb = 0
            rm = []

            for doc_key, doc_val in doc_copy.iteritems():
                if not validate(doc_key, key, False):
                    continue

                nb += 1

                if validate(doc_val, schema_val):
                    rm.append(doc_key)
                else:
                    return False

            if key.min is not None and nb < key.min:
                LOG.error("no enough document %r for qualifier: %r (min: %r, found: %r)", key.content, key.validator.__name__, key.min, nb)
                return False
            elif key.max is not None and nb > key.max:
                LOG.error("too many document %r for qualifier: %r (max: %r, found: %r)", key.content, key.validator.__name__, key.max, nb)
                return False
            else:
                for x in rm:
                    del doc_copy[x]
                continue

        for key, doc_val in doc_copy.iteritems():
            schema_val = optional.get(key, Nothing)
            if schema_val is Nothing:
                LOG.error("forbidden key %s in document", key)
                return False
            elif optionalnull.has_key(key) and doc_val is None:
                continue
            elif schema_val.min_len == 0 and doc_val is "":
                continue

            if schema_val.modifier:
                for modname in schema_val.modifier:
                    if modname in _modifiers:
                        document[key] = _modifiers[modname](document[key])
                        doc_val = _modifiers[modname](doc_val)
                    elif hasattr(doc_val, modname):
                        document[key] = getattr(document[key], modname)()
                        doc_val = getattr(doc_val, modname)()
                if optionalnull.has_key(key) and doc_val is None:
                    continue
                elif schema_val.min_len == 0 and doc_val is "":
                    continue

            if _valid_len(key, doc_val, schema_val.min_len, schema_val.max_len) is False:
                return False
            if not validate(doc_val, schema_val.content):
                return False
        return True
    elif isinstance(schema, list):
        if not isinstance(document, list):
            LOG.error("wanted a list, got a %s", document.__class__.__name__)
        for elt in document:
            # XXX: give a meaning when there are multiple element in a sequence of a schema?
            if len(schema) < 2:
                if not validate(elt, schema[0]):
                    return False
            elif isinstance(schema[0], dict):
                tmp = {}
                for x in schema:
                    for key, val in x.iteritems():
                        tmp[key] = val
                if not validate(elt, tmp):
                    return False
            else:
                if not validate(elt, schema[0]):
                    return False
        return True
    elif isinstance(schema, Any):
        return True
    elif isinstance(schema, Scalar):
        return helpers.is_scalar(document)
    else: # scalar
        if isinstance(schema, str):
            schema = unicode(schema)
        if isinstance(document, str):
            document = unicode(document, 'utf8')
        if schema.__class__ != document.__class__:
            LOG.error("wanted a %s, got a %s", schema.__class__.__name__, document.__class__.__name__)
            return False
        return True
1223142
def validateRoot(self, ctxt):
        
        if ctxt is None: ctxt__o = None
        else: ctxt__o = ctxt._o
        ret = libxml2mod.xmlValidateRoot(ctxt__o, self._o)
        return ret
954308
private void validate() {
        if (isValid != null) {
            return;
        }

        ParsingValidator v =
            new ParsingValidator(useSchema ? Languages.W3C_XML_SCHEMA_NS_URI
                                 : Languages.XML_DTD_NS_URI);
        List<Source> schemaSourceList = new ArrayList<Source>();
        if (systemId != null) {
            schemaSourceList.add(new StreamSource(systemId));
        }
        addSchemaSources(schemaSource, schemaSourceList);
        v.setSchemaSources(schemaSourceList.toArray(new Source[0]));

        try {
            ValidationResult r =
                v.validateInstance(new SAXSource(validationInputSource));
            isValid = r.isValid() ? Boolean.TRUE : Boolean.FALSE;
            for (ValidationProblem p : r.getProblems()) {
                validationProblem(p);
            }
        } catch (org.xmlunit.ConfigurationException e) {
            throw new ConfigurationException(e.getCause());
        } catch (org.xmlunit.XMLUnitException e) {
            throw new XMLUnitRuntimeException(e.getMessage(), e.getCause());
        }

        if (usingDoctypeReader && isValid == Boolean.FALSE) {
            try {
                messages.append("\nContent was: ")
                    .append(getOriginalContent(validationInputSource));
            } catch (IOException e) {
                // silent but deadly?
            }
        }
    }
454218
public static void validateXMLSchema(InputStream xsdStream, InputStream xmlStream) throws IOException, SAXException {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsdStream));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xmlStream));
    }
1182274
public void validate(EntityType entityType) {
    validateEntityId(entityType);
    validateEntityLabel(entityType);
    validatePackage(entityType);
    validateExtends(entityType);
    validateOwnAttributes(entityType);

    Map<String, Attribute> ownAllAttrMap =
        stream(entityType.getOwnAllAttributes())
            .collect(toLinkedMap(Attribute::getIdentifier, Function.identity()));

    validateOwnIdAttribute(entityType, ownAllAttrMap);
    validateOwnLabelAttribute(entityType, ownAllAttrMap);
    validateOwnLookupAttributes(entityType, ownAllAttrMap);
    validateLabelAttribute(entityType);
    validateBackend(entityType);
  }
109591
def validate(self, schema_str, xml_valid):
        
        # 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