tags:

views:

45

answers:

2

I have this function for validate xml messages against external schema file:

    private bool IsValidMessage(string message, XmlDocument xDoc)
 { 
  this.valid = true;

  byte[] bytes = Encoding.UTF8.GetBytes(message);

  MemoryStream ms = new MemoryStream(bytes);
  ms.Flush();
  ms.Position = 0;        


  XmlReaderSettings xSettings = new XmlReaderSettings();
  xSettings.ValidationType = ValidationType.Schema;

  xSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
  xSettings.Schemas.Add(null, "message.xsd");
  xSettings.ValidationEventHandler += delegate(object sender, ValidationEventArgs e) {
   this.valid = false;
   ShowMessage("Wrong message format: " + message);
  };

  XmlReader xReader = XmlReader.Create(ms, xSettings);                 
  xDoc.Load(xReader);              
  return valid;
 }

When I call IsValidMesage("nothing", xDoc); it returns true and code in validationEventHandler delegate never executes...(load throws exception but i think it should be taken care of in the delegate...) Do you have any idea why?

A: 

Think I found the reason, but this is only my guess:

When in string that should represent a proper xml document is just some string (like "nothing" in example) the validation would not happen becouse load throws exception that this isn't an xml at all.

Adrian Serafin
A: 

http://msdn.microsoft.com/en-us/library/ms162371.aspx

I think you need to do:

xmlDoc.Validate(eventhandler);
Rashmi Pandit