When the data we deal with becomes complex, its definition also becomes complex. Sometimes we handle this complexity via a lone XSD file until we reach a limit when maintainability, reusability, and scalability start to suffer. Then, we have to break up the XSD into multiple files. This post demonstrates how to validate an XML against an XSD that imports other XSD files, which differs from validating against multiple XSD files independently.
An XSD file That Imports Other XSD files
For our purpose, we have four XSD files to validate XML files against. First, we have the CommonTypes.xsd, which imports nothing and contains the common elements the other XSD files use. Then, we have the CustomerTypes.xsd, and OrderTypes.xsd. These files import the CommonTypes.xsd file. Finally, we have the Main.xsd, which imports the other three files.
Java codes To Validate XML
Consider the following two Java code snippets that validate an XML using the main XSD, which imports the other XSD files. First, we need a Schema object to validate an XML file against an XSD. We create the Schema object using the SchemaFactory and the main XSD file – Main.xsd. Since the main XSD file imports the other XSD files, we do not need to specify them in the Java codes.
1 2 3 4 5 6 7 8 9 10 | private static Schema getSchemaToValidateAgainst() throws Exception { // We reference the main XSD that imports other XSD files String mainXsdStr = "myxsds/Main.xsd"; SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schema = schemaFactory.newSchema( ComTurretaXmlValidationMultipleImportedXsdApplication.class.getClassLoader().getResource(mainXsdStr)); return schema; } |
Then, we use the Schema object to validate the XML file CustomerDetails01.xml against our main XSD file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | ... Schema schema = getSchemaToValidateAgainst(); try { // Validates CustomerDetails01.xml schema.newValidator().validate( new StreamSource( new File( ComTurretaXmlValidationMultipleImportedXsdApplication.class.getClassLoader().getResource( "xml/CustomerDetails01.xml").getFile()))); System.out.println("No Exceptions thrown. CustomerDetails01.xml is valid!"); } catch(Exception e) { System.out.println("Exceptions thrown. CustomerDetails01.xml is invalid!"); } ... |
When we run the codes, we get the following sample output.
Download the codes
We can check and download the Java codes in GitHub.