XSD - Validation

We'll use Java based XSD validator to validate students.xml against the students.xsd.


<?xml version = "1.0"?>

   <student rollno = "393">
   <student rollno = "493">	 
   <student rollno = "593">    


<?xml version = "1.0"?>

<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
   <xs:element name = 'class'>
             <xs:element name = 'student' type = 'StudentType' minOccurs = '0' 
                maxOccurs = 'unbounded' />

   <xs:complexType name = "StudentType">
         <xs:element name = "firstname" type = "xs:string"/>
         <xs:element name = "lastname" type = "xs:string"/>
         <xs:element name = "nickname" type = "xs:string"/>
         <xs:element name = "marks" type = "xs:positiveInteger"/>
      <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>


import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
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 XSDValidator {
   public static void main(String[] args) {
      if(args.length !=2){
         System.out.println("Usage : XSDValidator <file-name.xsd> <file-name.xml>" );
      } else {
         boolean isValid = validateXMLSchema(args[0],args[1]);
            System.out.println(args[1] + " is valid against " + args[0]);
         } else {
            System.out.println(args[1] + " is not valid against " + args[0]);
   public static boolean validateXMLSchema(String xsdPath, String xmlPath){
      try {
         SchemaFactory factory =
            Schema schema = factory.newSchema(new File(xsdPath));
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new File(xmlPath)));
      } catch (IOException e){
         System.out.println("Exception: "+e.getMessage());
         return false;
      }catch(SAXException e1){
         System.out.println("SAX Exception: "+e1.getMessage());
         return false;
      return true;

Steps to validate XML against XSD

  • Copy the XSDValidator.java file to any location, say E: > java

  • Copy the students.xml to same location E: > java

  • Copy the students.xsd to same location E: > java

  • Compile XSDValidator.java using console. Make sure you have JDK 1.5 onwards installed on your machine and classpaths are configured. For details on how to use JAVA, see JAVA Tutorial

E:\java\javac XSDValidator.java
  • Execute XSDValidator with students.xsd and students.xml passed as argument.

E:\java\java XSDValidator students.xsd students.xml

Verify the output

You'll see the following result −

students.xml is valid against students.xsd
Kickstart Your Career

Get certified by completing the course

Get Started