java – 针对XSD验证XML

参见英文答案 > What’s the best way to validate an XML file against an XSD file?                                    12个
我需要使用给定的XSD文件验证XML文件.如果验证正常,我只需要方法返回true,否则返回false.
最佳答案
返回true或false(也不需要任何外部库):

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

转载注明原文:java – 针对XSD验证XML - 代码日志