Here is an example of using the javax.xml.validation libraries inside of java to validate using a .xsd file:
try {
// get new factory instance
var factory = javax.xml.validation.SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
// in this case we feed the .xsd file from a system variable named 'Employee.xsd'. This could be changed to a file or some other method to get the .xsd loaded
var schema = factory.newSchema(new javax.xml.transform.stream.StreamSource(new java.io.ByteArrayInputStream(qie.getVariable('Employee.xsd').getBytes())));
// Now we validate the current message using the schema validator created with the .xsd
var validator = schema.newValidator();
validator.validate(new javax.xml.transform.stream.StreamSource(new java.io.ByteArrayInputStream(source.getBytes())));
// log out the results of the validation
qie.warn('Validation Passed. Happy Days');
} catch (err) {
qie.warn('Validation Failed: ' + err);
}
Here is a sample XML that will pass validation.
<?xml version="1.0" encoding="UTF-8"?>
<empns:empRequest xmlns:empns="https://www.journaldev.com/Employee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.journaldev.com/Employee Employee.xsd ">
<empns:id>5</empns:id>
</empns:empRequest>
Here is a sample xml that will fail validation
<?xml version="1.0"?>
<Employee>
<name>Pankaj</name>
<age>29</age>
<role>Java Developer</role>
<gender>Male</gender>
</Employee>
Here is the XSD File
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.journaldev.com/Employee"
xmlns:empns="https://www.journaldev.com/Employee" elementFormDefault="qualified">
<element name="empRequest" type="empns:empRequest"></element>
<element name="empResponse" type="empns:empResponse"></element>
<complexType name="empRequest">
<sequence>
<element name="id" type="int"></element>
</sequence>
</complexType>
<complexType name="empResponse">
<sequence>
<element name="id" type="int"></element>
<element name="role" type="string"></element>
<element name="fullName" type="string"></element>
</sequence>
</complexType>
</schema>