Woodstox : Validate against XML Schema

Overview

This article demonstrates how to validate an XML document against an XML Schema by using Woodstox.

Create employeeSchema.xml as shown below.

It defines the employee element that contains id, name and salary sub-elements.

Create validEmployee.xml as shown below. It is in accordance with employeeSchema.xml described above.

Create invalidEmployee.xml as shown below.

Note that it is
not
in accordance with employee.dtd described above as it defines the ‘title’ element (see line 4 below) instead of ‘salary’ element.

Create TestXmlSchemaValidation class as shown below:

Use
XMLStreamReader2.validateAgainst()
method to validate the XML document against the XML schema (see line 29 below).

From the main method, first successfully validate the validEmployee.xml file (see line 45 below).

Then try to validate invalidEmployee.xml (see line 46 below)and verify that the validation fails .

The output of the program demonstrating both validation success and failure scenarios is shown below.

Download Source Code for this Program

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.