
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Validating XML
|
841
Discussion
The Solution illustrates how to use the XmlReader to validate the book.xml document
against a book.xsd XSD definition file. DTDs were the original way to specify the
structure of an XML document, but it has become more common to use XSD since it
reached W3C Recommendation status in May 2001. XDR was a predecessor of XSD
provided by Microsoft, and, while it might be encountered in existing systems, it
should not be used for new development.
The first thing to do is create an
XmlReader to hold your XSD (book.xsd). Add it to the
XmlSchemaSet (Schemas property) on the XmlReaderSettings object settings:
// Wire up handler to get any validation errors.
settings.ValidationEventHandler += settings_ValidationEventHandler;
// Set the validation type to schema.
settings.ValidationType = ValidationType.Schema;
// Add book.xsd.
settings.Schemas.Add(null, XmlReader.Create(@"..\..\Book.xsd"));
The preceding code also hooks up the schema-collection event handler for valida-
tion errors to the
settings_ValidationEventHandler function. It also sets the
ValidationType to Schema. Setting XmlReaderSettings.ValidationType to ValidationType.
Schema
tells the XmlReader to perform XML Schema validation.
To perform DTD validation, use a DTD and ValidationType.DTD, and
to perform