Reputation: 109289
I'm trying to validate an XML document against a schema (which is embedded in my program as a resource). I got everything to work, so I tried to test for errors by adding a second sibling node in the XML at a location where the schema specifies maxOccurs="1"
. The problem is that my ValidationEventHandler
is never getting called, also XmlDocument.Load()
is throwing an XmlSchemaValidationException
exception when I'd expected XmlDocument.Validate()
to do that.
This is the code I have:
private void ValidateUserData( string xmlPath )
{
var resInfo = Application.GetResourceStream( new Uri( @"MySchema.xsd",
UriKind.Relative ) );
var schema = XmlSchema.Read( resInfo.Stream, SchemaValidationCallBack );
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add( schema );
schemaSet.ValidationEventHandler += SchemaValidationCallBack;
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas = schemaSet;
settings.ValidationType = ValidationType.Schema;
XmlDocument doc = new XmlDocument();
using( XmlReader reader = XmlReader.Create( xmlPath, settings ) ) {
doc.Load( reader ); // <-- This line throws an exception if XML is ill-formed
reader.Close();
}
doc.Validate( SchemaValidationCallBack );// <-- This is never reached
}
private void SchemaValidationCallBack( object sender, ValidationEventArgs e )
{
Console.WriteLine( "SchemaValidationCallBack: " + e.Message );
}
How do I get the callback to be called so I can handle validation errors?
Thanks for your help!
Upvotes: 1
Views: 1900
Reputation: 746
You have to handle the ValidationEventHandler envet of XmlReaderSettings class.
The XmlSchemaSet.ValidationEventHandler event will be fired if your XSD file is invalid.
The XmlReaderSettings.ValidationEventHandler event will be fired if your XML violates your XSD.
Upvotes: 4