I did a reply to a post here on StackOverflow; though my code is pretty old - out of my project code - but as they say, old is gold, so here it goes.
Usage:
XMLValidator val = new XMLValidator(); if (!val.IsValidXml(File.ReadAllText(@"d:\Test2.xml"), @"D:\Test2.xsd")) MessageBox.Show(val.Errors);
Code:
public class CXmlValidator { private int nErrors = 0; private string strErrorMsg = string.Empty; public string Errors { get { return strErrorMsg; } } public void ValidationHandler(object sender, ValidationEventArgs args) { nErrors++; strErrorMsg = strErrorMsg + args.Message + "\r\n"; } public bool IsValidXml(string strXml/*xml in text*/, string strXsdLocation /*Xsd location*/) { bool bStatus = false; try { // Declare local objects XmlTextReader xtrReader = new XmlTextReader(strXsdLocation); XmlSchemaCollection xcSchemaCollection = new XmlSchemaCollection(); xcSchemaCollection.Add(null/*add your namespace string*/, xtrReader);//Add multiple schemas if you want. XmlValidatingReader vrValidator = new XmlValidatingReader(strXml, XmlNodeType.Document, null); vrValidator.Schemas.Add(xcSchemaCollection); // Add validation event handler vrValidator.ValidationType = ValidationType.Schema; vrValidator.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); //Actual validation, read conforming the schema. while (vrValidator.Read()) ; vrValidator.Close();//Cleanup //Exception if error. if (nErrors > 0) { throw new Exception(strErrorMsg); } else { bStatus = true; }//Success } catch (Exception error) { bStatus = false; } return bStatus; } }
Here is a kb that demonstrates the use of several types of validation. This site provides Xml/Schema validation online.
Following is the code using non deprecated methods.
public bool IsValidXmlEx(string strXmlLocation, string strXsdLocation) { bool bStatus = false; try { // Declare local objects XmlReaderSettings rs = new XmlReaderSettings(); rs.ValidationType = ValidationType.Schema; rs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings; rs.ValidationEventHandler += new ValidationEventHandler(rs_ValidationEventHandler); rs.Schemas.Add(null, XmlReader.Create(strXsdLocation)); using (XmlReader xmlValidatingReader = XmlReader.Create(strXmlLocation, rs)) { while (xmlValidatingReader.Read()) { } } ////Exception if error. if (nErrors > 0) { throw new Exception(strErrorMsg); } else { bStatus = true; }//Success } catch (Exception error) { bStatus = false; } return bStatus; } void rs_ValidationEventHandler(object sender, ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Warning) strErrorMsg += "WARNING: " + Environment.NewLine; else strErrorMsg += "ERROR: " + Environment.NewLine; nErrors++; strErrorMsg = strErrorMsg + e.Exception.Message + "\r\n"; }
Happy validation!