Last active
July 29, 2020 12:01
-
-
Save automatonic/4331bb4157ab35176916 to your computer and use it in GitHub Desktop.
Programmatically validate an XML document with an XSD (XML Schema)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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