Reputation: 4815
I have a war file which is deployed on tomcat server. This war has xsd file at location webcontent -> WEB-INF -> resources -> HumanActivitySchema.xsd
I have a java class which is trying to load the schema to validate the input xml structure. This java class is part of war file deployment.
My java code function looks like:
public boolean validateXMLSchema(String iActivity){
Source schemaFile = new StreamSource(getClass().getClassLoader()
.getResourceAsStream("HumanActivitySchema.xsd"));
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new StringReader(iActivity)));
}
catch (IOException | SAXException e) {
if(DBG){
System.out.println("Error Message while validating activity : " + e.getMessage());
}
return false;
}
return true;
}
But the issue with this code is, it is not finding xsd file. So all fields of schemaFile are null. As a result exception is thrown at factory.newSchema(schemaFile) point.
Can anyone tell me what I am doing wrong and what changes I should do so that I can load my .xsd file?
Upvotes: 0
Views: 621
Reputation: 12817
You have two alternatives:
Put your XSD in on the classpath by placing it in the WEB-INF/classes directory, and load it with:
getClass().getClassLoader() .getResourceAsStream("/HumanActivitySchema.xsd")
Note the preceding slash ('/'). You can also place it in a folder matching the package name of your Java class, and the omit the preceding '/'.
Read the XSD through the ServletContext#getResourceAsStrem(String path) method. In your case the path would be
/HumanActivitySchema.xsd
Upvotes: 1