XML Schema Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.11

Validating XML Documents again Schema Documents

This section describes a tutorial example of how to use JAXP (Java API for XML Processing) to validate an XML document against a schema.

From the JAXP chapter of this book, we wrote a Java validator, XsdSchemaValidator.java, to validate XML documents again schema documents. Now we can use it to validate the following XML document, holiday_error.xml, again the holiday.xsd schema described in the previous section.

<?xml version="1.0"?>
<holiday country="Canada">National Day
<date>July 1</date>
</holiday>

Obviously, we are going to get several validation errors. Here is the entire output from XsdSchemaValidator.java:

>java XsdSchemaValidator holiday.xsd holiday_error.xml

Error:
   Line number: 2
   Column number: 27
   Message: cvc-type.3.1.1: Element 'holiday' is a simple type, 
   so it cannot have attributes, excepting those whose namespace
   name is identical to 'http://www.w3.org/2001/XMLSchema-instance'
   and whose [local name] is one of 'type', 'nil', 'schemaLocation'
   or 'noNamespaceSchemaLocation'. However, the attribute, 
   'country' was found.

Error:
   Line number: 4
   Column number: 11
   Message: cvc-type.3.1.2: Element 'holiday' is a simple type, so
   it must have no element information item [children].

Error:
   Line number: 4
   Column number: 11
   Message: cvc-datatype-valid.1.2.1: '' is not a valid value for 
   'date'.

Error:
   Line number: 4
   Column number: 11
   Message: cvc-type.3.1.3: The value '' of element 'holiday' is 
   not valid.

Failed with errors: 4

I assume that you know why we are getting those errors.

Table of Contents

 About This Book

 Introduction to XML Schema

 XML Editor and Schema Processor - XMLPad

 Java API for XML Processing - JAXP

 JAXP - XML Schema (XSD) Validation

 XML Parser API - Xerces2 Java Parser

XML Schema Language - Basics

 Schema and Schema XML Representation

 Checking Schema Documents - XsdSchemaChecker.java

 Creating Schema Documents - "schema" Element

 Declaring Root Elements - "element" Element

 Specifying Element Datatype - "type" Attribute

 Using XML Schema Built-in Datatypes

 Using XML Schema Built-in Datatypes Incorrectly

Validating XML Documents again Schema Documents

 Deriving New Simple Datatypes - "simpleType" Element

 Defining Complex Datatypes - "complexType" Element

 Validation Error Examples on Complex Datatypes

 XML Schema Built-in Datatypes

 Complex Element Declaration

 XML Schema Location and Namespace in XML Documents

 Overriding Element Types in XML Documents

 Linking Multiple Schema Documents Together

 Glossary

 References

 PDF Printing Version

Dr. Herong Yang, updated in 2009
Validating XML Documents again Schema Documents