Validating a XmlDocument using a schema in .Net 1.1 is not as easy as it should be (but it is fixed in System.Xml 2.0). XmlDocuments are really meant for updating Xml using the Document Object Model, but for some reason WSE and ASMX likes to return XmlDocuments, even though you are more likely to be reading the XML more then updating. If you want to validate an XML stream that you received thru a web service call, getting an XmlDocument instead of a XmlReader is a bit of a pain in .Net. At TechEd I had someone come up with a this issue, so I created the following ValidatingXmlDocument class based on System.Xml.XmlDocument. It is sort of like the new XmlDocument in System.Xml 2.0, but not as full featured. Since the person that had this problem was using VB.Net, I wrote this in their preferred programming language.
Imports System
Imports System.Xml
Imports System.IO
Imports System.Xml.Schema
Public Class ValidatingXmlDocument
Inherits XmlDocument
#Region "Private Fields"
Dim _Schemas As Schema.XmlSchemaCollection
Dim _IsValidDocument As Boolean = False
#End Region
#Region "Constructors"
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal doc As XmlDocument)
MyBase.New()
Dim TempMemoryStream As New MemoryStream
doc.Save(TempMemoryStream)
TempMemoryStream.Position = 0
MyBase.Load(TempMemoryStream)
_Schemas = New Schema.XmlSchemaCollection
End Sub
#End Region
Public Property Schemas() As Schema.XmlSchemaCollection
Get
Return _Schemas
End Get
Set(ByVal Value As Schema.XmlSchemaCollection)
_Schemas = Value
End Set
End Property
Public ReadOnly Property IsValidDocument() As Boolean
Get
Return _IsValidDocument
End Get
End Property
Public Event ValidationEventHandler As ValidationEventHandler
Public Sub Validate()
If ((Me.Schemas Is Nothing) OrElse (Me.Schemas.Count = 0)) Then
Throw New InvalidOperationException
End If
Try
Dim TempMemoryStream As New MemoryStream
Me.Save(TempMemoryStream)
TempMemoryStream.Position = 0
Dim Reader As New XmlTextReader(TempMemoryStream)
Dim validator As New XmlValidatingReader(Reader)
AddHandler validator.ValidationEventHandler, AddressOf Validator_ValidationEventHandler
validator.Schemas.Add(_Schemas)
_IsValidDocument = True
While validator.Read()
End While
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Private Sub Validator_ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)
_IsValidDocument = False
RaiseEvent ValidationEventHandler(Me, args)
End Sub 'ValidationEventHandle
End Class