Both, Java and XML are spread widely and used intensively. This post sheds some light onto the possibilities on validating XML files with the JAVA API. In all code listings, the exception handling is omitted as well as the imports. The classes used are from the
java.xml.validation packages. Moreover, this post focus on simple validation code snippets.
First, we can check if the XML file is well-formed. This can be done by parsing the XML file into a DOM document.
Next, it is possible to validate the XML file against a XML schema. However, in this case we validate the XSD file first to ensure that it is valid itself.
With the valid XSD file we can validate the XML file against this schema.
As quite some XML files do use multiple XML Schemas, the code above will always fail. Therefore, we need to create a
Schema which consists of multiple XSD files.
When shipping the XSD files within the jar, it is required to reference them by resource instead.