Skip to main content

Validating XML documents with schema in JAXP 1.3

Posted by kohsuke on June 1, 2006 at 4:15 PM PDT

Question: "I have a schema, and I want to validate documents by using it before I process them. How do I do that?"

Answer: this is supposed to be really really easy with JAXP 1.3. First, you parse your schema and build a schema object, like this:

class Foo {
  private static final Schema SCHEMA;
  static {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SCHEMA = schemaFactory.newSchema(MyClass.class.getResource("myschema.xsd");
  }
}

If you'll be using this schema to parse more than one document, it's a good idea to reuse the same Schema object, as it's expensive to create. Schema object is thread-safe, so the simplest way to do it is to store it in a static variable.

Then to parse a document, do as follows. Notice that you don't want to do spf.setValidating(true); since what it really means is to enable DTD validation on, as specified by the XML recommendation (more precisely it just makes your parser "validating parser" from "non-validating parser")

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setSchema(SCHEMA);

SAXParser parser = parserFactory.newSAXParser();
parser.parse(...);

That's it. This is supposed to be pretty easy.

Related Topics >>