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
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:
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.