Validating XML against XSD

Shai picture Shai · Jul 25, 2011 · Viewed 61.9k times · Source

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.

Answer

Grzegorz Szpetkowski picture Grzegorz Szpetkowski · Jul 25, 2011

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