XmlDocument.Load() throws XmlSchemaValidationException

Posted by Praetorian on Stack Overflow See other posts from Stack Overflow or by Praetorian
Published on 2011-01-18T03:45:46Z Indexed on 2011/01/18 3:53 UTC
Read the original article Hit count: 243

Filed under:
|
|

Hi, 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!

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml