Skip to main content

XSD Schema Validation

The other day I was writing a .NET application which would read all the configuration details from an xml file.The application was not going to initialize properly unless the data in the config file were well formed.So I was wondering whether there was a way to validate an xml against some defined XSD schema.
Thankfully there is.
This is how I did it.
.............................................

//Open the file with xml reader
XmlTextReader reader = new XmlTextReader(configFilePath);//Some local path

// Read the Schema
XmlReader schemaReader = new XmlTextReader(schemaPath);//path of the XSD file
XmlSchema schema = XmlSchema.Read(schemaReader , null);

// Create a validating Reader for the text reader
XmlValidatingReader validatingReader = new XmlValidatingReader(reader );
validatingReader.ValidationType = ValidationType.Schema;
validatingReader.Schemas.Add(schema);// Add the Schema to validatingReader
validatingReader.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandle); //Event Handler for Validation Error
while (validatingReader.Read()) { } // Read but do nothing

.............................................

If the xml file is a valid one then the validatingReader won't fire any events.

(a better approach...)
Even I managed to figure out a way to validate an XML file with a given Schema, I was wondering why we would need two readers to read/validate just one file. Then I figured out that XmlValidatingReader has now become obsolete.And instead, this task could be performed using just one Reader. We just need to put all the validation setting while creating the Reader itself.
.............................................

// Read the XSD file and build schema object out of it
XmlReader schemaReader = new XmlTextReader(@"Schema.xsd");
XmlSchema schema = XmlSchema.Read(schemaReader, null);

//Create XmlReaderSettings object with validation settings
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(schema);

//Assign the ValidationEvent Handler
settings.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandle);

//Now create the reader with Validation Setting
XmlReader myXmlReader = XmlReader.Create(filePath,settings);

// Read XML data
while (myXmlReader.Read()) { }

.............................................

If the XML file fails to validate against the given schema, the validation event will be fired.

For Reference : http://msdn2.microsoft.com/en-us/library/9d83k261%28VS.80%29.aspx

Comments