Private Function ValidateVsSchema(ByVal strXMLFile As String, ByVal strXMLSchema As String) As Boolean
Dim lReturn As Boolean = True
Try
'load schema from file
Dim objReader As StreamReader
objReader = New StreamReader(strXMLSchema)
Dim strXsdContents As String
strXsdContents = objReader.ReadToEnd()
objReader.Close()
'load xml from file
Dim strXMLContents As String
objReader = New StreamReader(strXMLFile)
strXMLContents = objReader.ReadToEnd()
objReader.Close()
' read the schema into a stream...
Dim clsStream As New MemoryStream()
Dim bSchema As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(strXsdContents)
clsStream.Write(bSchema, 0, bSchema.Length)
clsStream.Flush()
clsStream.Position = 0
' load the schema into a schema object...
Dim clsSchema As Schema.XmlSchema = Schema.XmlSchema.Read(clsStream, Nothing)
clsStream.Close()
clsStream.Dispose()
' configure the reader to use validation, and add the schema we just loaded...
Dim clsReaderSettings As New XmlReaderSettings()
clsReaderSettings.ValidationType = ValidationType.Schema
clsReaderSettings.Schemas.Add(clsSchema)
' read xml into a stream and then into an XmlReader...
clsStream = New MemoryStream()
Dim bXml As Byte() = System.Text.Encoding.ASCII.GetBytes(strXMLContents)
clsStream.Write(bXml, 0, bXml.Length)
clsStream.Flush()
clsStream.Position = 0
Dim clsReader As XmlReader = XmlReader.Create(clsStream, clsReaderSettings)
Dim lCount As Integer = 1
Do While Not clsReader.EOF
Try
clsReader.Read()
Catch exXml As System.Xml.XmlException
WriteLog(String.Concat("Xml Error: ", exXml.Message), Color.Chocolate)
lReturn = False
Catch exXsd As System.Xml.Schema.XmlSchemaException
WriteLog(String.Concat("> ", exXsd.Message), Color.DarkGreen)
lReturn = False
Catch ex As Exception
'WriteLog(String.Concat("General Error: ", ex.Message))
lReturn = False
Finally
lCount = lCount + 1
End Try
Loop
clsStream.Close()
clsStream.Dispose()
clsReader.Close()
Catch ex As Exception
MessageBox.Show(Me, String.Concat("General Error: ", ex.Message))
lReturn = False
End Try
Return lReturn
End Function
You can cut and paste this function on your VB .NET project then just pass the location of your XML and schema (.xsd) file. Please take note of the WriteLog function, it uses textbox to display status messages.
0 comments:
Post a Comment