Click here to Skip to main content
12,943,913 members (59,115 online)
Click here to Skip to main content


60 bookmarked
Posted 20 May 2005

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

, 26 May 2005 CPOL
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()

        'This call is required by the Windows Form Designer.

        '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
            End If
        End If
    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.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MIFile, Me.MIAbout})
        Me.MIFile.Index = 0
        Me.MIFile.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MILine, Me.MIExit})
        Me.MIFile.Text = "&File"
        Me.MILine.Index = 0
        Me.MILine.Text = "-"
        Me.MIExit.Index = 1
        Me.MIExit.Text = "E&xit"
        Me.MIAbout.Index = 1
        Me.MIAbout.Text = "&About"
        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 = ""
        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:"
        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 = ""
        Me.btnopen.Location = New System.Drawing.Point(356, 8)
        Me.btnopen.Name = "btnopen"
        Me.btnopen.TabIndex = 6
        Me.btnopen.Text = "Open"
        Me.OFDialog.Filter = "XML files|*.XML|XSD files|*.XSD|All files|*.*"
        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"
        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"
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(652, 273)
        Me.Menu = Me.MainMenu1
        Me.Name = "frmMain"
        Me.Text = "Simple XML Validator"

    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
    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
            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.")
            Exit Sub
        End If

            writertbox("Validating XML against schema (XSD) starting...")
            writertbox("on " + txtfilexml.Text)
            'Try to validate the xml file
            If validatexml(txtfilexml.Text) Then
                writertbox("XML File has successfully been validated against the schema")
                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
        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.

        '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
            sr = New StreamReader(infilename)
            myschema = XmlSchema.Read(sr, AddressOf ValidationCallBack)
            'This compile statement is what ususally catches the errors
            myschema.Compile(AddressOf ValidationCallBack)

        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 + "" + 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.")
            Exit Sub
        End If


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

            End If

        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.


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


About the Author

Software Developer (Senior)
United States United States
I started my programmer career over 21 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 when the beta 2 came out in 2001. After spending most of my programming life as a windows programmer I started to check out in 2004. I achieved my 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 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 VS2015.

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.

You may also be interested in...

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170518.1 | Last Updated 26 May 2005
Article Copyright 2005 by kubben
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid