It seems like validating an XML document against a schema would be a pretty simple thing to do in the .Net framework, seeing as how they have such deep support for dealing with XML.
But as of yet, I haven’t found a simple way to do it.
Here is the code I have been using to validate XML against an XML Schema.
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Private schemaValidation As New ValidationEventHandler(AddressOf ValidationHandler)
Private Function ValidateXml(ByVal xmlFileName As String, ByVal xmlSchemaName As String) As Boolean
Using myFile As New FileStream(xmlFileName, FileMode.Open, FileAccess.Read, FileShare.None)
Dim xDoc As New Xml.XmlDocument()
xDoc.Load(myFile)
xDoc.Schemas.Add(GetSchema(xmlSchemaName))
Try
xDoc.Validate(schemaValidation)
Return True
Catch ex As XmlSchemaValidationException
Console.Write(ex.ToString)
Return False
Catch ex As XmlSchemaException
Console.Write(ex.ToString)
Return False
Catch ex As Exception
Console.Write(ex.ToString)
Return False
End Try
End Using
End Function
Private Function GetSchema(ByVal filePath As String) As XmlSchema
Dim schema As XmlSchema
Using s As New System.IO.FileStream(filePath, FileMode.Open)
Using reader As New StreamReader(s)
schema = XmlSchema.Read(reader, Nothing)
End Using
End Using
Return schema
End Function
Private Sub ValidationHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs)
Throw e.Exception
End Sub
Thank you so much for this! It seems there still isn’t a great way to do this even with VS2008. This example is great!
You’re welcome!
Hi Chris,
Thanks for the code. Is this still the best way to do it?
I can’t see anything new in VS2010.