Validating XML against XSD [duplicate]

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

XMLUnit has some nice classes to do this, there is an example in their README file:

Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
v.setSchemaSources(Input.fromFile("local.xsd").build());
ValidationResult result = v.validateInstance(new StreamSource(new File("local.xml")));
return result.isValid();

public boolean validate() {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  factory.setValidating(true);

  factory.setAttribute(
        "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
        "http://www.w3.org/2001/XMLSchema");
  factory.setAttribute(
        "http://java.sun.com/xml/jaxp/properties/schemaSource",
        "http://domain.com/mynamespace/mySchema.xsd");
  Document doc = null;
  try {
    DocumentBuilder parser = factory.newDocumentBuilder();
    doc = parser.parse("data.xml");
    return true;
  } catch (Exception e) {
    return false;
  }
}

This might depends on the library you use but googling around with "how to validate xml file in java" gave me these results where you might find your answer:

first interesting result

second interesting result