
  |   I want my samples in...      

How Do I...? Common Tasks QuickStart Tutorial

How Do I...Apply Validation When Reading XML?

This sample illustrates how to apply validation when reading and parsing XML data using the XmlReader class. Validation is the process of enforcing rules on the XML content either via a Document Type Definition (DTD) or a XML Schema Definition language (XSD) schema.

VB ValidationReadingXML.exe
View Source
[This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\Xml\ValidationReadingXml\]

The XmlReader class can provide validation of a DTD or an XML Schema when parsing the document. XmlReader objects are created with the Create method. Settings on the XmlReaderSettings class determine what features are supported on the XmlReader object.

This sample validates several XML files, using both DTD and XML Schema validation. It shows validation successes and failures.

The following code sets a ValidationEventHandler to handle validation error results. If a handler is not provided, an XmlSchemaException is thrown when a validation error occurs.

XmlReaderSettings settings = new XmlReaderSettings(); 
settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandler);

The validation settings are specified with the DtdValidate or XsdValidate properties on the XmlReaderSettings class. The default setting for both properties is false so the XmlReader does not validate. The following code creates a DTD validating XmlReader object for the Validate subroutine.

settings.DtdValidate = true;
Validate(XmlReader.Create(XmlReader.Create(document1), settings));

As the XmlReader parses the XML document, it calls the validation event handler when it encounters a validation error. The parser only stops if the parser finds data that is not well-formed. By not stopping for validation errors, you are able to find all the validation errors in one pass without having to repeatedly parse the XML document.


  1. Validation can either be against a DTD or an XML Schema. The validation setting is specified with the DtdValidate or the XsdValidate properties on the XmlReaderSettings class.
  2. Validation is performed during the read and parsing operations.
  3. A ValidationEventHandler must be set to receive notification of validation errors.
  4. Validation errors do not stop parsing. Parsing only stops if there is a well-formedness error. This enables all errors to be discovered in a single pass.

Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.