Note: [Mar 23, 2017] This website was migrated to a new platform recently. Some linked content may not be accessible until all the links are configured properly,

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 java.io.File;
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
 * http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM8.html
 *
 * 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
            = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    static final String W3C_XML_SCHEMA 
            = "http://www.w3.org/2001/XMLSchema";
    static final String JAXP_SCHEMA_SOURCE
            = "http://java.sun.com/xml/jaxp/properties/schemaSource";
     
    public static void main(String[] args) {
        if(args.length != 2) {
            System.err.println(
                    "Usage: java XMLSchemaValidator schemafile.xsd xmlfile.xml");
            System.exit(1);
        }
         
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
         
        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.
            parser.parse(args[1]);
             
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 

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 XMLSchemaValidator.java. Compile it as follows:

javac XMLSchemaValidator.java

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

java XMLSchemaValidator myschema.xsd myxmldoc.xml