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

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.

Sections in This Chapter

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

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