Thursday, October 1, 2009

Validating XML against an XSD, .net

Following code will validate an XML file agaisnt an XSD stored in a file system and stored all the errors encoutered


Public Function ValidatingProcess(ByVal XSDPath As String, ByVal XMLPath As String, ByVal ValidationErrorsSavePath As String)

Try

' 1- Read XML file content
Reader = New XmlTextReader(XMLPath)

' 2- Read Schema file content
SR = New StreamReader(XSDPath)

' 3- Create a new instance of XmlSchema object
Dim Schema As XmlSchema = New XmlSchema



' 4- Set XmlSchema object by calling XmlSchema.Read() method
' Schema = XmlSchema.Read(SR, new ValidationEventHandler(ValidatingReader_ValidationEventHandler));
Schema = XmlSchema.Read(SR, New ValidationEventHandler(AddressOf ValidatingReader_ValidationEventHandler))

'Addhandler SR,

'AddHandler Reader.ValidationEventHandler, AddressOf Me.ValidatingReader_ValidationEventHandler

' 5- Create a new instance of XmlValidationReader object
Dim ValidatingReader As XmlValidatingReader = New XmlValidatingReader(Reader)

' 6- Set ValidationType for XmlValidationReader object
ValidatingReader.ValidationType = ValidationType.Schema

' 7- Add Schema to XmlValidationReader Schemas collection
ValidatingReader.Schemas.Add(Schema)

' 8- Add your ValidationEventHandler address to
' XmlValidationReader's ValidationEventHandler
'ValidatingReader.ValidationEventHandler += New ValidationEventHandler(ValidatingReader_ValidationEventHandler)
AddHandler ValidatingReader.ValidationEventHandler, AddressOf ValidatingReader_ValidationEventHandler

test:

Try

' 9- Read XML content in a loop
While (ValidatingReader.Read())

End While
Catch

GoTo test
End Try

SaveErrorsToAFile(ValidationErrorsSavePath, Me.Results)


'Handle exceptions if you want
Catch AccessEx As UnauthorizedAccessException

Throw AccessEx

Catch Ex As Exception
Throw Ex
End Try

End Function


Private Sub ValidatingReader_ValidationEventHandler(ByVal sender As Object, ByVal args As System.Xml.Schema.ValidationEventArgs)

' 10- Implement your logic for each validation iteration
Dim strTemp As String
strTemp = "Line: " + Me.Reader.LineNumber.ToString() + " - Position: " + Me.Reader.LinePosition.ToString() + " - " + args.Message

Me.Results.Add(strTemp)
End Sub


Private Function SaveErrorsToAFile(ByVal filepath As String, ByVal errors As ArrayList) As Boolean

Dim blnSuccess As Boolean = False

Try

Dim tw As TextWriter = New StreamWriter(filepath, False)

'/ write a line of text to the file
Dim e As IEnumerator = errors.GetEnumerator()

While (e.MoveNext())
tw.WriteLine(e.Current.ToString())
End While
' close the stream
tw.Close()
blnSuccess = True

Catch
blnSuccess = False
End Try

Return blnSuccess
End Function



References

http://aspalliance.com/941

No comments:

Post a Comment