Skip to content

Instantly share code, notes, and snippets.

@Garren
Created February 28, 2012 18:49
Show Gist options
  • Save Garren/1934285 to your computer and use it in GitHub Desktop.
Save Garren/1934285 to your computer and use it in GitHub Desktop.
Programmatically validate against a schema (pulled from an SO post and slightly modified)
class Program {
static void Main(string[] args) {
var doc = ".\\file.xml";
var xsd = ".\\schema.xsd";
var settings = new XmlReaderSettings {
CloseInput = true,
ValidationType = ValidationType.Schema,
ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings
| XmlSchemaValidationFlags.ProcessIdentityConstraints
| XmlSchemaValidationFlags.ProcessInlineSchema
| XmlSchemaValidationFlags.ProcessSchemaLocation
};
settings.ValidationEventHandler += (o, e) => {
if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
System.Diagnostics.Trace.WriteLine(
String.Format("Line: {0}, Position: {1} \"{2}\"",
e.Exception.LineNumber, e.Exception.LinePosition,
e.Exception.Message));
};
settings.Schemas.Add(null, xsd);
using (var validatingReader = XmlReader.Create(new StringReader(doc), settings)) {
while (validatingReader.Read()) { /* just loop through document */ }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment