Validate XML against XSD Schema using Java

In this example we will Validate XML against XSD Schema. We use the javax.xml.validation.Validator to check the XML document against the XSD schema. Be careful because the validator is not thread safe. It is the responsibility of the application to make the code thread safe. The validation is successful when the validator.validate() method does not throw an exception.

Project structure

|   +--main
|       +--java
|           +--com
|               +--memorynotfound
|                   |
|       +--resources
|           |--schema.xsd

XSD Schema

<xs:schema xmlns:xs="">

    <xs:element name="course">
                <xs:element type="xs:string" name="name"/>
                <xs:element type="xs:string" name="description"/>
            <xs:attribute type="xs:integer" name="id"/>


XSD Validator

To validate XML against XSD schema we need to create a schema and a validator. Next we validate the XML against the XSD schema. The validation is successful if the validator.validate() method does not throw an exception.

Warning: A validator is NOT thread save. It is the responsibility of the application to make sure that one Validator object is not used from more than one thread at any given time.
package com.memorynotfound.xml.xsd;

import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

public class ValidateXmlXsd {

    public static String xml =
            "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
            "<course id=\"1-ID\">\n" +
            "    <name>JAX-B</name>\n" +
            "    <description>Validate XML against XSD Schema</description>\n" +

    public static void main(String... args) {
        try {
            System.out.println("Validate XML against XSD Schema");
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(ValidateXmlXsd.class.getResource("/schema.xsd"));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new StringReader(xml)));
            System.out.println("Validation is successful");
        } catch (IOException e) {
            // handle exception while reading source
        } catch (SAXException e) {
            System.out.println("Error when validate XML against XSD Schema");
            System.out.println("Message: " + e.getMessage());


Getting the line and column number

If you need to display the line or column number, read this tutorial.


Validate XML against XSD Schema
Error when validate XML against XSD Schema
Message: cvc-datatype-valid.1.2.1: '1-ID' is not a valid value for 'integer'.



You may also like...

  • James

    This would be more helpful if it would make validation errors available to the user.