I'm trying to validate an xml file using oasis catalog. What i need is to give the path of the xml file and the path of the catalog that contains the xsd as input and to get the validation (true or error message) as output.
What i have done so far is :
File schemaFile = new File("personal.xsd"); // etc.
Source xmlFile = new StreamSource(new File("personal.xml"));
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/XML/XMLSchema/v1.1"); // we need to validate with v1.1
try {
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {
e.printStackTrace();
}
So it's working so far.
The issue is to add the catalog. I found some code sample but it is not working :
Source xmlFile = new StreamSource(new File("personal.xml"));
String [] catalogs = {"file:///catalog.xml"};
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/XML/XMLSchema/v1.1");
try {
XMLCatalogResolver resolver = new XMLCatalogResolver();
resolver.setPreferPublic(true);
resolver.setCatalogList(catalogs);
schemaFactory.setResourceResolver(resolver);
Schema schema = schemaFactory.newSchema();
Validator validator = schema.newValidator();
validator.validate(xmlFile);
}
In the end, the xsd is not find and the validation fails.
Can someone explain me what i am doing wrong ? i feel like it should be simple but i'm missing something.
Thank.
After 2 weeks of research here my conclusion
I never managed to do it with Xerces-2j. You can do it with the xerces in the JRE (javaSE-1.8), here is how you can do it.
GL if you want to use xerces-2J