Validate a XDocument against schema without the ValidationEventHandler (for use in a HTTP handler)

Posted by Vaibhav Garg on Stack Overflow See other posts from Stack Overflow or by Vaibhav Garg
Published on 2010-02-26T11:39:57Z Indexed on 2010/04/16 10:33 UTC
Read the original article Hit count: 262

Hi everyone, (I am new to Schema validation)

Regarding the following method,

System.Xml.Schema.Extensions.Validate(
    ByVal source As System.Xml.Linq.XDocument, 
    ByVal schemas As System.Xml.Schema.XmlSchemaSet,
    ByVal validationEventHandler As System.Xml.Schema.ValidationEventHandler, 
    ByVal addSchemaInfo As Boolean)

I am using it as follows inside a IHttpHandler -

Try      
  Dim xsd As XmlReader = XmlReader.Create(context.Server.MapPath("~/App_Data/MySchema.xsd"))
  Dim schemas As New XmlSchemaSet() : schemas.Add("myNameSpace", xsd) : xsd.Close()
  myXDoxumentOdj.Validate(schemas, Function(s As Object, e As ValidationEventArgs) SchemaError(s, e, context), True)
Catch ex1 As Threading.ThreadAbortException
  'manage schema error'
  Return
Catch ex As Exception
  'manage other errors'
End Try

The handler-

  Function SchemaError(ByVal s As Object, ByVal e As ValidationEventArgs, ByVal c As HttpContext) As Object
    If c Is Nothing Then c = HttpContext.Current
    If c IsNot Nothing Then
      HttpContext.Current.Response.Write(e.Message)
      HttpContext.Current.Response.End()
    End If
    Return New Object()
  End Function

This is working fine for me at present but looks very weak. I do get errors when I feed it bad XML. But i want to implement it in a more elegant way. This looks like it would break for large XML etc.

Is there some way to validate without the handler so that I get the document validated in one go and then deal with errors?

To me it looks Async such that the call to Validate() would pass and some non deterministic time later the handler would get called with the result/errors. Is that right?

Thanks and sorry for any goofy mistakes :).

© Stack Overflow or respective owner

Related posts about .net-3.5

Related posts about xdocument