The XmlValidatingReader class, as its name implies, provides data validation capabilities. Specifically, it can validate XML data against a document type definition (DTD), an XML schema definition language (XSD) schema, or an XML Data Reduced (XDR) schema. This class does not work alone; it must be used in conjunction with an instance of XmlTextReader that is passed to the constructor. Thus, this class gives you the forward-only capabilities of XmlTextReader with validation added. XmlValidatingReader also adds support for default attributes and the ability to resolve external references. Validation of XML data is an inherently complex and slow process.
XmlValidatingReader validates as it goes along. To validate an entire XML file, you must step though it from beginning to end. In broad outline the procedure is as follows:
- Create an instance of the XmlTextReader class connected to the XML file.
- Create an instance of the XmlValidatingReader class and pass it a reference to the XmlTextReader class that was created in step 1.
- Create an event handler procedure to handle validation errors.
- Set the XmlValidatingReader object's ValidationType (DTD, XDR, or XSD) and ValidationEventHandler properties.
- If you are validating against an external XSD or XDR Schema, set the Schemas property to identify the Schema file.
- Call the XmlValidatingReader object's Read() method repeatedly until the end of the XML file is reached.
Validation errors will throw an exception, which you can catch using the handler created in step 3. If the process completes without an exception then the XML data is valid.