Validating an XML document against a given XML Schema in Java

Submitted by Kamal Wickramanayake on July 9, 2010 - 12:41

Many XML validators exist. Here's how you may implement an XML validator in Java. At times you may need to take a programmatic approach like this.

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 * This is an XML Schema validator written in Java.
 * The implementation is sketched at
 * Improvements required to the code to validate XML files with
 * multiple namespaces are also found at the above URL.
public class XMLSchemaValidator {
    static final String JAXP_SCHEMA_LANGUAGE
            = "";
    static final String W3C_XML_SCHEMA 
            = "";
    static final String JAXP_SCHEMA_SOURCE
            = "";
    public static void main(String[] args) {
        if(args.length != 2) {
                    "Usage: java XMLSchemaValidator schemafile.xsd xmlfile.xml");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);

        // Set the schema file
        factory.setAttribute(JAXP_SCHEMA_SOURCE, new File(args[0]));
        try {
            DocumentBuilder parser = factory.newDocumentBuilder();

            // Parse the file. If errors found, they will be printed.
        } catch (Exception e) {

What we do here is simply parsing an XML document. To do so, we create a DocumentBuilderFactory. We request the DocumentBuilderFactory to validate a given XML document against a given XML Schema document by invoking the setValidate() method of the factory. Just before we start parsing the XML document, we specify the XML Schema file by using the setAttribute(JAXP_SCHEMA_SOURCE,...) of the factory. Then we create a DocumentBuilder from the factory and invoke the parse() method of it. If the XML document is invalid, the catch block prints the details.

You can save the above in a file called Compile it as follows:


Validate an XML file against an XML Schema file as follows:

java XMLSchemaValidator myschema.xsd myxmldoc.xml