Created
June 12, 2015 14:43
-
-
Save csmoore/604142592047cbaf6f39 to your computer and use it in GitHub Desktop.
Simplest C# XSD Validator - console app to test validation
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
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).