Click here to Skip to main content
15,898,035 members
Articles / Programming Languages / XML

Simple code to validate an XML file against a schema file (XSD)

Rate me:
Please Sign up or sign in to vote.
3.66/5 (34 votes)
26 May 2005CPOL2 min read 427.1K   10.8K   60  
This article is about XML and XSD validation.
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Imports System.Globalization
Imports System.Reflection

Public Class frmMain
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
    Friend WithEvents Rtboxlog As System.Windows.Forms.RichTextBox
    Friend WithEvents txtfilexml As System.Windows.Forms.TextBox
    Friend WithEvents btnopen As System.Windows.Forms.Button
    Friend WithEvents btnValidate As System.Windows.Forms.Button
    Friend WithEvents btnXSD As System.Windows.Forms.Button
    Friend WithEvents MIFile As System.Windows.Forms.MenuItem
    Friend WithEvents MILine As System.Windows.Forms.MenuItem
    Friend WithEvents MIExit As System.Windows.Forms.MenuItem
    Friend WithEvents MIAbout As System.Windows.Forms.MenuItem
    Friend WithEvents lbValidate As System.Windows.Forms.Label
    Friend WithEvents OFDialog As System.Windows.Forms.OpenFileDialog
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.MainMenu1 = New System.Windows.Forms.MainMenu
        Me.MIFile = New System.Windows.Forms.MenuItem
        Me.MILine = New System.Windows.Forms.MenuItem
        Me.MIExit = New System.Windows.Forms.MenuItem
        Me.MIAbout = New System.Windows.Forms.MenuItem
        Me.Rtboxlog = New System.Windows.Forms.RichTextBox
        Me.lbValidate = New System.Windows.Forms.Label
        Me.txtfilexml = New System.Windows.Forms.TextBox
        Me.btnopen = New System.Windows.Forms.Button
        Me.OFDialog = New System.Windows.Forms.OpenFileDialog
        Me.btnValidate = New System.Windows.Forms.Button
        Me.btnXSD = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'MainMenu1
        '
        Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MIFile, Me.MIAbout})
        '
        'MIFile
        '
        Me.MIFile.Index = 0
        Me.MIFile.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MILine, Me.MIExit})
        Me.MIFile.Text = "&File"
        '
        'MILine
        '
        Me.MILine.Index = 0
        Me.MILine.Text = "-"
        '
        'MIExit
        '
        Me.MIExit.Index = 1
        Me.MIExit.Text = "E&xit"
        '
        'MIAbout
        '
        Me.MIAbout.Index = 1
        Me.MIAbout.Text = "&About"
        '
        'Rtboxlog
        '
        Me.Rtboxlog.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.Rtboxlog.Location = New System.Drawing.Point(0, 41)
        Me.Rtboxlog.Name = "Rtboxlog"
        Me.Rtboxlog.Size = New System.Drawing.Size(652, 232)
        Me.Rtboxlog.TabIndex = 3
        Me.Rtboxlog.Text = ""
        '
        'lbValidate
        '
        Me.lbValidate.AutoSize = True
        Me.lbValidate.Location = New System.Drawing.Point(12, 8)
        Me.lbValidate.Name = "lbValidate"
        Me.lbValidate.Size = New System.Drawing.Size(109, 16)
        Me.lbValidate.TabIndex = 4
        Me.lbValidate.Text = "XML File to Validate:"
        '
        'txtfilexml
        '
        Me.txtfilexml.Location = New System.Drawing.Point(124, 8)
        Me.txtfilexml.Name = "txtfilexml"
        Me.txtfilexml.Size = New System.Drawing.Size(224, 20)
        Me.txtfilexml.TabIndex = 5
        Me.txtfilexml.Text = ""
        '
        'btnopen
        '
        Me.btnopen.Location = New System.Drawing.Point(356, 8)
        Me.btnopen.Name = "btnopen"
        Me.btnopen.TabIndex = 6
        Me.btnopen.Text = "Open"
        '
        'OFDialog
        '
        Me.OFDialog.Filter = "XML files|*.XML|XSD files|*.XSD|All files|*.*"
        '
        'btnValidate
        '
        Me.btnValidate.Enabled = False
        Me.btnValidate.Location = New System.Drawing.Point(464, 8)
        Me.btnValidate.Name = "btnValidate"
        Me.btnValidate.Size = New System.Drawing.Size(80, 23)
        Me.btnValidate.TabIndex = 7
        Me.btnValidate.Text = "Validate XML"
        '
        'btnXSD
        '
        Me.btnXSD.Enabled = False
        Me.btnXSD.Location = New System.Drawing.Point(564, 8)
        Me.btnXSD.Name = "btnXSD"
        Me.btnXSD.Size = New System.Drawing.Size(80, 23)
        Me.btnXSD.TabIndex = 8
        Me.btnXSD.Text = "Validate XSD"
        '
        'frmMain
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(652, 273)
        Me.Controls.Add(Me.btnXSD)
        Me.Controls.Add(Me.btnValidate)
        Me.Controls.Add(Me.btnopen)
        Me.Controls.Add(Me.txtfilexml)
        Me.Controls.Add(Me.lbValidate)
        Me.Controls.Add(Me.Rtboxlog)
        Me.Menu = Me.MainMenu1
        Me.Name = "frmMain"
        Me.Text = "Simple XML Validator"
        Me.ResumeLayout(False)

    End Sub

#End Region
    Private m_Success As Boolean = True 'Was the validation successful?

    Private Sub MIExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MIExit.Click
        'Menu Exit click
        Close()
    End Sub

    Private Sub btnopen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnopen.Click
        'Click the open dialog button
        If OFDialog.ShowDialog = DialogResult.OK Then
            'They selected a file so put it in the text box
            txtfilexml.Text = OFDialog.FileName
        End If
    End Sub

    Private Sub Enabledisable(ByVal SetEnabled As Boolean)
        'A little sub to help enable and disable form controls when validating
        If SetEnabled Then
            btnopen.Enabled = True
            'looking for the correct extension to enable correct button
            btnValidate.Enabled = txtfilexml.Text.ToUpper.IndexOf(".XML") >= 0
            btnXSD.Enabled = txtfilexml.Text.ToUpper.IndexOf(".XSD") >= 0
        Else
            btnopen.Enabled = False
            btnValidate.Enabled = False
            btnXSD.Enabled = False
        End If
    End Sub
    Private Sub btnValidate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValidate.Click
        'The clicked the validate xml button
        If Not File.Exists(txtfilexml.Text) Then
            'File doesn't existing, must have miss typed it.
            MessageBox.Show("You need to put a valid file name in the text box.")
            txtfilexml.Focus()
            Exit Sub
        End If
        Try
            writertbox("")
            writertbox("-------------------------")
            writertbox("")

            writertbox("Validating XML against schema (XSD) starting...")
            writertbox("on " + txtfilexml.Text)
            Enabledisable(False)
            'Try to validate the xml file
            If validatexml(txtfilexml.Text) Then
                writertbox("XML File has successfully been validated against the schema")
            Else
                writertbox("XML File failed validation against the schema." + vbCrLf + "NOTE the xml file needs to point to the schema file (xsd)." + vbCrLf + "The xsd file must be in the same dir as the xml file.")
            End If
        Finally
            Enabledisable(True)
        End Try
    End Sub
    Private Function validatexml(ByVal infile As String) As Boolean
        'First we create the xmltextreader
        Dim xmlr As New XmlTextReader(infile)
        'We pass the xmltextreader into the xmlvalidatingreader
        'This will validate the xml doc with the schema file
        'NOTE the xml file it self points to the schema file
        Dim xmlvread As New XmlValidatingReader(xmlr)

        ' Set the validation event handler
        AddHandler xmlvread.ValidationEventHandler, AddressOf ValidationCallBack
        m_Success = True 'make sure to reset the success var

        ' Read XML data
        While (xmlvread.Read)
        End While
        'Close the reader.
        xmlvread.Close()

        'The validationeventhandler is the only thing that would set m_Success to false
        Return m_Success

    End Function
    Private Sub ValidationCallBack(ByVal sender As Object, ByVal args As ValidationEventArgs)
        'Display the validation error.  This is only called on error
        m_Success = False 'Validation failed
        writertbox("Validation error: " + args.Message)
    End Sub
    Private Function validateSchema(ByVal infilename As String) As Boolean
        'this function will validate the schema file (xsd)
        Dim sr As StreamReader
        Dim myschema As XmlSchema
        m_Success = True 'make sure to reset the success var
        Try
            sr = New StreamReader(infilename)
            myschema = XmlSchema.Read(sr, AddressOf ValidationCallBack)
            'This compile statement is what ususally catches the errors
            myschema.Compile(AddressOf ValidationCallBack)

        Finally
            sr.Close()
        End Try
        Return m_Success
    End Function
    Private Sub writertbox(ByVal instr As String)
        'this will always append the log info with the time and date stamp
        Rtboxlog.AppendText(Now.ToString("hh:mm:ss yyyy/MM/dd", DateTimeFormatInfo.InvariantInfo) + " " + instr + vbCrLf)
    End Sub

    Private Sub MIAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MIAbout.Click
        'Get the assemblyname object based off the name of this application
        'NOTE the version is pulled from the assemblyinfo.vb file
        Dim tmpName As AssemblyName = AssemblyName.GetAssemblyName(Application.ExecutablePath)
        'Show the assemblyVersion
        MessageBox.Show("Simple XML Validator" + vbCrLf + "By: Ben Kubicek" + vbCrLf + "ben.kubicek@netzero.com" + vbCrLf + "Version: " + tmpName.Version.ToString(), "Version", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Private Sub txtfilexml_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtfilexml.TextChanged
        'looking for the correct extension to enable correct button
        btnValidate.Enabled = txtfilexml.Text.ToUpper.IndexOf(".XML") >= 0
        btnXSD.Enabled = txtfilexml.Text.ToUpper.IndexOf(".XSD") >= 0
    End Sub

    Private Sub btnXSD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXSD.Click
        'Validate schema file click
        If Not File.Exists(txtfilexml.Text) Then
            'File doesn't exist must have mis-typed it.
            MessageBox.Show("The file is not found.")
            txtfilexml.Focus()
            Exit Sub
        End If

        Try
            writertbox("")
            writertbox("-------------------------")
            writertbox("")

            writertbox("Schema File Validating Starting...")
            writertbox("on " + txtfilexml.Text)
            Enabledisable(False)
            'Try to validate the schema file
            If validateSchema(txtfilexml.Text) Then
                writertbox("XSD Schema File has successfully been validated.")
            Else
                writertbox("XSD Schema File has Failed validation.")

            End If

        Finally
            Enabledisable(True)
        End Try
    End Sub
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
I started my programmer career over 26 years ago doing COBOL and SAS on a MVS mainframe. It didn't take long for me to move into windows programming. I started my windows programming in Delphi (Pascal) with a Microsoft SQL server back end. I started working with vb.net when the beta 2 came out in 2001. After spending most of my programming life as a windows programmer I started to check out asp.net in 2004. I achieved my MCSD.net in April 2005. I have done a lot of MS SQL database stuff. I have a lot of experience with Window Service and Web services as well. I spent three years as a consultant programing in C#. I really enjoyed it and found the switch between vb.net and C# to be mostly syntax. In my current position I am programming in C# working on WPF and MSSql database stuff. Lately I have been using VS2019.

On a personal note I am a born again Christian, if anyone has any questions about what it means to have a right relationship with God or if you have questions about who Jesus Christ is, send me an e-mail. ben.kubicek[at]netzero[dot]com You need to replace the [at] with @ and [dot] with . for the email to work. My relationship with God gives purpose and meaning to my life.

Comments and Discussions