Woodstox : Validate against XML Schema


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.

Download Source Code for this Program

1 thought on “Woodstox : Validate against XML Schema”

  1. Very nice article, execpt for one thing.

    This is not the right way to read an XSD schema from classpath:
    InputStream schemaInputStream = getClass().getResourceAsStream(relaxNgFileName);
    XMLValidationSchema xmlValidationSchema = xmlValidationSchemaFactory.createSchema(schemaInputStream);

    The above only works if your schema does not import another schema using relative path. If it does, the relative path will be resolved against the directory from which your code is run and not against the path of your schema, which will most likely cause an error.

    To solve this issue, you shoud load your schema like this:
    URL schemaUrl = getClass().getResource(relaxNgFileName);
    XMLValidationSchema xmlValidationSchema = xmlValidationSchemaFactory.createSchema(schemaUrl);


Leave a Comment