Richard’s Weblog

July 16, 2009

XML Schema validation with XMLReader (xerces 2)

Filed under: Uncategorized — Richard @ 12:17 pm
Tags: , , ,

Today I struggled for a long time trying to do a simple thing : Validating an xml file against an XML Schema, using a SAX parser (xerces2), in java. I’m pretty new to the XML validation stuff. I didn’t want the xsd to be specified in the xml file, nor I didn’t want to have my xsd publicly available, so I decided to keep it in the classpath. Unfortunately, I didn’t find how to do that directly on the Internet. So, trying things and other things, I managed to make it, so here’s the code :

  URL schemaLocation = this.getClass().getClassLoader().getResource("com.myPackage.mySchema.xsd");
  XMLReader parser = XMLReaderFactory.createXMLReader();
  parser.setFeature("http://xml.org/sax/features/validation", true);
  parser.setFeature("http://apache.org/xml/features/validation/schema", true);
  parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
    schemaLocation.toExternalForm());
  parser.setContentHandler(new IndexationHandler(this));
  parser.parse(new InputSource(is));

Setting the property “http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation” will tell the parser to use my xsd file in the class path. The “trick” I had not figured out at the begining is that JAVA can generate an URL pointing to a file residing in the classpath.

PS : In this example I did’t specify any ErrorHandler to manage the validation, so validation errors will only appears in the console during the parsing.

Blog at WordPress.com.