In the scope of different projects I often have to validate XML files. Here is my solution to verify XML files using a schema.

First of all to validate XML files in Java you need create a SchemaFactory of the W3C XML schema language and you have to compile the schema (let’s assume it’s located in /path/to/schema.xsd ):

SchemaFactory factory = SchemaFactory.newInstance ("");
Schema schema = factory.newSchema (new File ("/path/to/schema.xsd"));

Now you’re able to create a validator from the schema.

Validator validator = schema.newValidator ();

In order to validate a XML file you have to read it (let’s assume it’s located in /path/to/file.xml ):

Source source = new StreamSource (new File ("/path/to/file.xml"));

Last but not least you can validate the file:

  validator.validate (source);
  System.out.println ("file is valid");
catch (SAXException e)
  System.out.println ("file is invalid:");
  System.out.println (e.getMessage ());
Download: JAVA: (Please take a look at the man-page. Browse bugs and feature requests.)

Martin Scharm

stuff. just for the records.

1 Comment

Andrew Werner | Permalink | 2013-12-15 19:41:01

After panicking and scouring the web for 2 days, this has been the ONLY website that has been able to help me! Thank you so so much!

Post a comment

read more about submitting comments