Categories
General

Validating an XML document against a schem

How to validate an XML document against a schema, and one error you can avoid…

Share

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

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Share