It's pretty fiddly, here's my code:
''' <summary>
''' Validates an XML stream against the specified XML Schema. Raises
ValidateXmlFileException if the XML stream or XML Schema fails validation.
''' </summary>
'''
'''
'''
''' <exception cref="ValidateXMLFileException">Raised if XML or XML
File fails validation</exception>
''' <remarks></remarks>
Public Sub ValidateXmlFile(ByVal SchemaNamespace As String, ByVal
SchemaStream As Stream, ByVal XmlStream As Stream)
' Create the XmlSchemaSet class.
Dim sc As XmlSchemaSet = New XmlSchemaSet()
Try
' Add the schema to the collection.
Dim xrInput As New XmlTextReader(SchemaStream)
sc.Add(SchemaNamespace, xrInput)
' Set the validation settings.
Dim settings As XmlReaderSettings = New XmlReaderSettings()
settings.ValidationType = ValidationType.Schema
settings.Schemas = sc
AddHandler settings.ValidationEventHandler, AddressOf
ValidateXmlFile_Callback
' Create the XmlReader object.
Using reader As XmlReader = XmlReader.Create(XmlStream,
settings)
' Parse the file.
Do While reader.Read() : Loop
End Using
If mstrValidateXmlFileErrorMessage > "" Then
Throw New ValidateXMLFileException("The XML Stream
failed validation", New ApplicationException(mstrValidateXmlFileErrorMessage))
End If
RemoveHandler settings.ValidationEventHandler, AddressOf
ValidateXmlFile_Callback
Catch ex As XmlSchemaException
Throw New ValidateXMLFileException("Could not parse schema",
ex)
Catch ex As XmlException
Throw New ValidateXMLFileException("Could not parse XML", ex)
End Try
End Sub
Private Sub ValidateXmlFile_Callback(ByVal sender As Object, ByVal e
As ValidationEventArgs)
mstrValidateXmlFileErrorMessage = e.Message
End Sub
Public Class ValidateXMLFileException
Inherits Exception
Sub New(ByVal ErrorMessage As String, ByVal InnerException As
Exception)
MyBase.New(ErrorMessage, InnerException)
End Sub
End Class
--
David Streeter
Synchrotech Software
Sydney Australia