Sunday, February 2, 2014
XSD (XML Schema Definition) represent the content model or grammar of an XML document. XML schema defines the elements that form an XML document.Validation is the process of verifying if the XML document complies to the defined schema definition.

Let us consider a simple XML file and the corresponding schema definition.

<?xml version="1.0"?>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <description>An in-depth look at creating applications 
      with XML.</description>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <description>After the collapse of a nanotechnology 
      society in England, the young survivors lay the 
      foundation for a new society.</description>

The schema definition.
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
  <xs:element name="catalog">
        <xs:element name="book" maxOccurs="unbounded" minOccurs="0">
              <xs:element type="xs:string" name="author"/>
              <xs:element type="xs:string" name="title"/>
              <xs:element type="xs:string" name="genre"/>
              <xs:element type="xs:float" name="price"/>
              <xs:element type="xs:date" name="publish_date"/>
              <xs:element type="xs:string" name="description"/>
            <xs:attribute type="xs:string" name="id" use="optional"/>

Java program to validate XML against the XSD

package com.sourcetricks.validate;


import javax.xml.XMLConstants;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

public class ValidateXML {

 public static void main (String[] args) {
  try {
   // SchemaFactory for schema language W3C XML Schema 1.0
   SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
   // Parse xsd a provides a schema object
   Schema schema = schemaFactory.newSchema(new File("resources/input.xsd"));
   // Processor to check XML is valid against schema
   Validator validator = schema.newValidator();
   // Validates the specified input
   validator.validate(new StreamSource(new File("resources/input.xml")));
  } catch ( SAXException e ) {
   // SAXException provides the validation errors 
  } catch ( IOException e ) {


When there are errors we get a SAXException. For example try changing id to id1 in the attribute of input XML.
cvc-complex-type.3.2.2: Attribute 'id1' is not allowed to appear in element 'book'.

Try the SmallWebTools - Free online XML validator against XSD

Contact Form


Email *

Message *

Back to Top