In days on .Net 2.0, its was not straight forward to validate and XML with XSD. We were doing lot of coding playing around with XmlTextReader and XmlValidatingReader. Thanks to .Net 3.5 where majority of the functionality is provided by the XMLDocument itself. Below is the piece of code to validate and XML document against XSD.
Below is the event handler to handle the validation event, we need to add this to the event handler collection, this becomes the input parameter for validate function.
protected void ValidationHandler(object sender,
ValidationEventArgs args)
{
// code you want to execute when validation error/warning is raised
ErrorMessage += "
" + args.Message + "\r\n";
ErrorsCount++;
}
Below is the code snippet to validate the xml against XSD, below snippet assumes that XSD file resides in the same folder as XML.
XmlDocument xx = new XmlDocument();
xx.Load(xmlFilePath);
xx.Schemas.Add("",Path.Combine(Path.GetDirectoryName(xmlFilePath),
"ConfigurationSchema.xsd"));
// create an eventhandler with function coded above
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationHandler);
//Validate the XML
xx.Validate(eventHandler);
validation event is raised for every error/waring while validating, so you can process each error message separately as required