Java, Software Development

Validate XML against an XSD that imports other XSDs

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.

Then, we use the Schema object to validate the XML file CustomerDetails01.xml against our main XSD file.

When we run the codes, we get the following sample output.

Download the codes

We can check and download the Java codes in GitHub.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like