Skip to content

Instantly share code, notes, and snippets.

@csmoore
Created June 12, 2015 14:43
Show Gist options
  • Save csmoore/604142592047cbaf6f39 to your computer and use it in GitHub Desktop.
Save csmoore/604142592047cbaf6f39 to your computer and use it in GitHub Desktop.
Simplest C# XSD Validator - console app to test validation
using System;
using System.Xml;
using System.Xml.Schema;
namespace ValidationTests
{
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
string schemaFile = @"Test.xsd";
XmlTextReader schemaReader = new XmlTextReader(schemaFile);
XmlSchema schema = XmlSchema.Read(schemaReader, SchemaValidationHandler);
xmlDoc.Schemas.Add(schema);
string filename = @"FileToValidate.xml";
xmlDoc.Load(filename);
xmlDoc.Validate(DocumentValidationHandler);
}
private static void SchemaValidationHandler(object sender, ValidationEventArgs e)
{
System.Console.WriteLine(e.Message);
}
private static void DocumentValidationHandler(object sender, ValidationEventArgs e)
{
System.Console.WriteLine(e.Message);
}
}
}
@aleksandarjoksimovic
Copy link

aleksandarjoksimovic commented Jan 23, 2024

Problem with this validation is that XmlDocument.Validate exits with first exception (i.e. on first invalid element in XML). This is not to obvious from the MSDN documentation but still it's there. In most cases we would like to provide all issues to our client's just from single run of XmlDocument.Validate (and not just our clients, we as developers would also like to see the whole document being validated). So this is a big con of using such validation approach (and currently I don's see a way to bypass it).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment