Validating XML with XSD (Java)

This validates an XML with an XSD scheme which must not necessarily be stated in the XML file. By using the SchemaFactory the program does not build all DOM objects for the document and thus is faster and not so memory intensive as the DOMParser approach.

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;


public class XmlValidator
{
 public static void main(String[] args)
 {
  try {
      

      SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

      Schema sch= schemaFactory .newSchema(new StreamSource("D:\\example.xsd"));
      Validator validator = sch.newValidator();

      validator.validate(new StreamSource("D:\\example.xml"));
      
      System.out.println("Successfully validated");

  } catch (Exception e) {
      e.printStackTrace();
  } 
  
  
 }
}