How to validate XML against XSD in Java With Examples

Java XML Validation API can be used to validate XML against XSD in java program. javax.xml.validation.Validator class is used in this program to validate xml against xsd in java.

Validate XML against XSD

Here are the sample XSD and XML files used.

Employee.xsd

Notice that above XSD contains two root element and namespace also, I have created two sample XML file from XSD using Eclipse.

EmployeeRequest.xml

EmployeeResponse.xml

Here is another XML file that doesn’t confirms to the Employee.xsd.

employee.xml

Here is the program that is used to validate all three XML files against the XSD. The validateXMLSchema method takes XSD and XML file as argument and return true if validation is successful or else returns false.

XMLValidation.java

Output of the above program is:

The benefit of using Java XML validation API is that we don’t need to parse the file and there is no third party APIs used.

By admin

Leave a Reply