Skip to content

Instantly share code, notes, and snippets.

@automatonic
Last active July 29, 2020 12:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save automatonic/4331bb4157ab35176916 to your computer and use it in GitHub Desktop.
Save automatonic/4331bb4157ab35176916 to your computer and use it in GitHub Desktop.
Programmatically validate an XML document with an XSD (XML Schema)
//License: MIT
//using System.Xml;
//using System.Xml.Schema;
public static List<ValidationEventArgs> ValidateXmlWithXsd(string xmlPath, string xsdPath)
{
XmlSchemaSet s = new XmlSchemaSet();
var args = new List<ValidationEventArgs>();
using (XmlReader reader = XmlReader.Create(xsdPath))
{
//These validations will be from reading the xsd itself
s.Add(XmlSchema.Read(reader,(obj, e) => args.Add(e)));
//Add more to the set if you have additional...
}
XmlDocument document = new XmlDocument();
document.Schemas = s;
document.Load(xmlPath);
//These will be from applying the schema rules to the incoming document
document.Validate((obj, e) => args.Add(e));
//See ValidationEventArgs.Severity for details on Errors vs Warnings
//http://msdn.microsoft.com/en-us/library/system.xml.schema.validationeventargs.severity.aspx
return args;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment