Skip to content

Instantly share code, notes, and snippets.

@antiduh
Created September 3, 2015 22:41
Show Gist options
  • Save antiduh/223522a5d93cda823851 to your computer and use it in GitHub Desktop.
Save antiduh/223522a5d93cda823851 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
namespace TestProject
{
/// <summary>
/// Simple program to manually validate an XML document against a schema.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
string schemaLocation = @"schema.xsd";
string docLocation = @"document.xml";
// --------------------- Schema ---------------------
Console.Out.WriteLine( "Loading schema..." );
XmlSchema schema;
FileStream schemaStream;
schemaStream = new FileStream( schemaLocation, FileMode.Open, FileAccess.Read, FileShare.Read );
schema = XmlSchema.Read( schemaStream, SchemaValidationHandler );
Console.Out.WriteLine( "Loading schema...done" );
Console.Out.WriteLine();
// --------------------- Document ---------------------
Console.Out.WriteLine( "Loading document..." );
XmlDocument doc;
XmlReaderSettings docReaderSettings;
XmlReader docReader;
docReaderSettings = new XmlReaderSettings();
docReaderSettings.ValidationType = ValidationType.Schema;
docReaderSettings.ValidationFlags =
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ReportValidationWarnings;
docReaderSettings.ValidationEventHandler += DocValidationHandler;
docReaderSettings.Schemas.Add( schema );
docReader = XmlReader.Create( docLocation, docReaderSettings );
doc = new XmlDocument();
doc.Load( docReader );
Console.Out.WriteLine( "Loading document...done" );
Console.Out.Flush();
}
private static void SchemaValidationHandler( object node, ValidationEventArgs args )
{
Console.Out.WriteLine( args.Message );
}
private static void DocValidationHandler( object node, ValidationEventArgs args )
{
Console.Out.WriteLine( args.Message );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment