14.5. Validating an XML Document with a DTD

Problem

You want to verify that an XML document is valid according to a DTD.

Solution

Use the Xerces library with either the SAX2 (Simple API for XML) or the DOM parser.

To validate an XML document using SAX2, obtain a SAX2XMLReader, as in Example 14-8. Next, enable DTD validation by calling the parser’s setFeature() method with the arguments xercesc::XMLUni::fgSAX2CoreValidation and true. Finally, register an ErrorHandler to receive notifications of DTD violations and call the parser’s parse() method with your XML document’s name as its argument.

To validate an XML document using DOM, first construct an instance of XercesDOMParser. Next, enable DTD validation by calling the parser’s setValidationScheme( ) method with the argument xercesc:: XercesDOMParser::Val_Always. Finally, register an ErrorHandler to receive notifications of DTD violations and call the parser’s parse( ) method with your XML document’s name as its argument.

Tip

Here I’m using the class XercesDOMParser, an XML parser that has been part of Xerces since before the DOM Level 3 DOMBuilder interface was introduced. Using a XercesDOMParser makes the example a bit simpler, but you can use a DOMBuilder instead if you like. See Discussion and Recipe 14.4.

For example, suppose you modify the XML document animals.xml from Example 14-1 to contain a reference to an external DTD, as illustrated in Examples Example 14-11 and Example 14-12. The code to validate this document using the SAX2 ...

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.