Validate XML Against XSD [XML SCHEMA] using C#
In this blog post, we will see how to create an XML schema file for an xml file and how to validate if a certain XML complies to our schema.
First of all, open the XML file in Visual Studio. Right click the solution explorer select add Existing file and select the xml file. Open the file and choose from the menu XML --> Create Schema.
Now you have the schema and the XML file, it is time to write some code to validate the xml file.
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, XSDFILEPATH);
settings.ValidationType = ValidationType.Schema;
XmlDocument document = new XmlDocument();
document.Load(XMLFILEPATH);
XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);
while(rdr.Read()){}
}
catch
{
isValid = false;
}
if the validation fails, a private field is set to false (isValid) in which you can check at runtime to see if the status of the validation process.
Hope this helps,