Thursday, October 8, 2009

How to validate XML string using XSD file

I have spended quite some time looking for a .net 3.5 compatible implementation of XML validation with XSD. Since i could not find one I wrote my own, bases on 2.0 implementation that I did find. Here it is:

Imports System.Text
Imports System.Xml.Schema
Imports System.Xml

Public Class XMLValidator2
  ' Validation Error Count
  Shared ErrorsCount As Integer = 0
  ' Validation Error Message
  Shared ErrorMessage As String = ""

  ' Validation Error Count
  Shared XSDErrorsCount As Integer = 0
  ' Validation Error Message
  Shared XSDErrorMessage As String = ""

  Public Sub Validate(ByVal strXMLDoc As String, ByVal xsdFilePath As String)

  
    Dim strXMLReader As New IO.StringReader(strXMLDoc)
    Dim schemaTextReader As IO.TextReader = New IO.StreamReader(xsdFilePath)

    Dim readerSettings As XmlReaderSettings = New XmlReaderSettings()
    'NOTE: če bomo kdaj javno objavili shemo lahko za path damo url
    readerSettings.Schemas.Add(XmlSchema.Read(schemaTextReader, AddressOf XSDSchemaValidationHandler))
    readerSettings.ValidationType = ValidationType.Schema
    AddHandler readerSettings.ValidationEventHandler, New ValidationEventHandler(AddressOf ValidationHandler)

    Dim books As XmlReader = XmlReader.Create(strXMLReader, readerSettings)

    While books.Read()

    End While

    ' Raise exception, if XML validation fails
    If ErrorsCount > 0 Then
      Throw New ApplicationException(ErrorMessage)
    End If

    ' XML Validation succeeded
    Console.WriteLine("XML validation succeeded." & vbCr & vbLf)

  End Sub

  Private Sub ValidationHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)
    ErrorMessage = ErrorMessage + args.Message & vbCr & vbLf
    ErrorsCount += 1
  End Sub

  Private Sub XSDSchemaValidationHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)
    XSDErrorMessage = XSDErrorMessage + args.Message & vbCr & vbLf
    XSDErrorsCount += 1
  End Sub


End Class
Post a Comment