14.6. Validating an XML Document with a Schema

Problem

You want to verify that an XML document is valid according to a schema, as specified in the XML Schema 1.0 recommendation.

Solution

Use the Xerces library with either the SAX2 or the DOM parser.

Validating an XML document against a schema using the SAX2 API is exactly the same as validating a document that contains a DTD, assuming the schema is contained in or referenced from the target document. If you want to validate an XML document against an external schema, you must call the parser’s setProperty() method to enable external schema validation. The first argument to setProperty() should be XMLUni::fgXercesSchemaExternalSchemaLocation or XMLUni::fgXercesSche-maExternalNoNameSpaceSchemaLocation, depending on whether the schema has a target namespace. The second argument should be the location of the schema, expressed as a const XMLCh*. Make sure to cast the second argument to void*, as explained in Recipe 14.5.

Validating an XML document against a schema using the XercesDOMParser is similar to validating a document against a DTD, assuming the schema is contained in or referenced from the target document. The only difference is that schema and namespace support must be explicitly enabled, as shown in Example 14-15.

Example 14-15. Enabling schema validation with a XercesDOMParser

XercesDOMParser parser;
parser.setValidationScheme(XercesDOMParser::Val_Always);
parser.setDoSchema(true);
parser.setDoNamespaces(true);

If you want to validate ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.