针对 XSD 验证 XML

针对 XSD 验证 XML

问题描述:

我需要使用给定的 XSD 文件验证 XML 文件.如果验证正常,我只需要该方法返回 true 否则返回 false.

I need to validate an XML file with a given XSD file. I simply need the method to return true if the validation went fine or false otherwise.

简单地返回真或假(你也不需要任何外部库):

Returns simply true or false (also you don't need any external library):

static boolean validateAgainstXSD(InputStream xml, InputStream xsd)
{
    try
    {
        SchemaFactory factory = 
            SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xml));
        return true;
    }
    catch(Exception ex)
    {
        return false;
    }
}