Home » Java » Sample code to load & validate an XML file & schema in Saxon under Java-Exceptionshub

Sample code to load & validate an XML file & schema in Saxon under Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

This is for a tool in our system that will verify that it can load an XML file with Saxon, and list any problems. So I want to have Saxon load the file and throw an exception if it can’t fully parse it. This test has an option to be given a schema file so it validates against the schema if it exists.

This is for our Java version so need to use the Java API. I tried to port over the C# Validate example (there is no Java validate that I could find) but the API is quite a bit different.

And if possible, get a list of errors it found parsing.

How to&Answers:

In the download file you should find samples/java/ee/SchemaValidatorExample.java which uses the JAXP interface, and also java/he/S9APIExamples.java which uses the s9api API and includes use cases SchemaA and SchemaB.

These could do with updating, none of them takes advantage of the new interface SchemaValidator.setInvalidityHandler() which allows you either to supply an instance of InvalidityReportGeneratorEE which gives you a Saxon-generated report of all invalidities found, or your own InvalidityReportGenerator or InvalidityHandler to produce your own customized reporting. I suggest you take a tour of the Javadoc for documentation of what these do.

These are very much geared to custom reporting of the invalidities found. Throwing an exception if the file isn’t valid is much simpler.