Web Service That Validates Incoming Messages According to a Schema

To validate messages at the service use the XmlValidatingReader. The best place
to validate messages is in a SOAP Extension. This gives you complete control over
the contents of the SOAP message and allows you to reject messages that are not
schema-compliant before the relatively expensive deserialization step.

Note that this sample validates messages in the body of the WebMethod instead.
This is done for simplicity. The steps to validate the message are the same
regardless of location. For more information about validation in SOAP
extensions, refer to this MSDN article.

//create the validating reader
XmlTextReader tr = new XmlTextReader(input, XmlNodeType.Document, null);
XmlValidatingReader vr = new XmlValidatingReader(tr);
//add the schema and set the validation type to schema
XmlSchemaCollection schemas = new XmlSchemaCollection();
schemas.Add("Microsoft.Samples.Web.Services", "insert location here...");
vr.Schemas.Add(schemas);
vr.ValidationType = ValidationType.Schema;
//add our event callback function to the event handler in case there is a validation error
vr.ValidationEventHandler += new ValidationEventHandler (ValidationHandler);
try
{
//if there is an error we will fall out of this while loop and our callback function will be called
while (vr.Read())
{
//do nothing
}
}
catch (Exception exception)
{
//an exception will be thrown if there are non-validation errors, e.g. in the case of malformed XML
}