I am trying to validate an XML against multiple XSD, and I have come up with this code. But the issue is when I keep a debugger at the validateXML
method to check the schema object, I see only one file in fGrammarDescription, which is always the first file in the schemaname.
So finally, tags from other xsd's are not recognized and hence failing the validation.
public class TestMain {
public static void main(String[] args) {
TestMain testMain = new TestMain();
String schemaName1 = "1.xsd";
String schemaName2 = "2.xsd";
String schemaName3 = "3.xsd";
String schemaName4 = "4.xsd";
String schemaName5 = "5.xsd";
String xmlName = "C:\\Users\\nagesingh\\IdeaProjects\\test.xml";
Schema schema = testMain.loadSchema(schemaName1, schemaName2, schemaName3,schemaName4,schemaName5);
Document document = parseXmlDom(xmlName);
validateXml(schema, document);
}
public static void validateXml(Schema schema, Document document) {
try {
// 3. Get a validator from the schema.
Validator validator = schema.newValidator();
System.out.println("Validator Class: " + validator.getClass().getName());
// validating the document against the schema
validator.validate(new DOMSource(document));
System.out.println("Validation passed.");
} catch (Exception e) {
// catching all validation exceptions
System.out.println(e.toString());
}
}
public Schema loadSchema(String... schemaFileName) {
Schema schema = null;
try {
String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
SchemaFactory factory = SchemaFactory.newInstance(language);
List<Source> sourceList = new ArrayList<>();
List<String> stringList = Arrays.asList(schemaFileName);
for (String eachSchemaFile : stringList){
sourceList.add(new StreamSource(getClass().getClassLoader().getResource("xml/"+eachSchemaFile).toExternalForm()));
}
schema = factory.newSchema(sourceList.stream().toArray(Source[]::new));
} catch (Exception e) {
System.out.println(e.toString());
}
return schema;
}
public static Document parseXmlDom(String xmlName) {
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(new File(xmlName));
} catch (Exception e) {
System.out.println(e.toString());
}
return document;
}
}