根据XSD验证XML

根据XSD验证XML

问题描述:

我需要使用给定的XSD文件验证XML文件。我只需要方法返回true,如果验证变好或否则。

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;
    }
}