November 20th, 2005


20
Nov 05

Validating an XML document against a schem

To validate the XML files I am generating against a schema, I used this very simplistic code:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);

factory.setNamespaceAware(true);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

Schema schema = schemaFactory.newSchema(new File("my-schema.xsd"));

factory.setSchema(schema);

Document doc = factory.newDocumentBuilder().parse(new File("my-file.xml"));

If anything is invalid, exceptions are thrown.

Be sure to include the following line:

factory.setNamespaceAware(true);

otherwise you will get this cryptic error:
cvc-complex-type.3.2.2: Attribute 'xsi:noNamespaceSchemaLocation' is not allowed to appear in element ...

Share