Click here to Skip to main content
15,861,168 members
Articles / Programming Languages / XML
Article

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 424.6K   10.8K   60   41
This article is about XML and XSD validation.

Image 1

Introduction

I had a need to validate an XML file against a schema file (XSD) in VB.NET. So I wrote a simple app that could do this validation. While I was at it I decided it might be nice to validate the schema file all by itself. The basic core functions could be reused in your code to validate XML files against a schema, or just validate the schema file by itself. So I spent an hour or two to put this SimpleXMLValidator together. Most of the code can be found in partial form in the Visual Studio help files.

Background

I started working on a project where I had the option to use a flat file fixed length format or XML file with a schema. Since there was the need to verify that we didn't lose any data on the transfer of the file to our system, I decided on the XML file with schema (not that I would ever choose a flat file over XML). I figured this would also help catch any changes to the XML format. You know how vendors change their format and don't tell you. Then it is a big guessing game to what changed. This little app helps you identify what is wrong, so you know where to look for, to fix the problem.

The code

There are two functions and one sub that do the real work. Each of the functions calls a delegate (which is the one sub) if a validation error occurs. Note that the signature of the sub is important, (that is, the input variables to the procedure must match the delegate signature). All I am really doing in this sub is setting a variable to mark the file as failed validation and displaying the error in a RichTextBox. Here's the code:

VB
'vb.net
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
C#
//C#
private void ValidationCallBack(Object sender, ValidationEventArgs args)
    {
       //Display the validation error.  This is only called on error
       m_Success = false; //Validation failed
       writertbox("Validation error: " + args.Message);
    }

Next we have the XML validation code. Really the only important prerequisite is that the XML file should point to the correct schema file (XSD) inside the XML file on the XSI tag.

Here is an example:

XML
<?xml version="1.0" encoding="utf-8"?>
<ROOTElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="yourschema.xsd">

Here is the code for the XML validation function:

VB
'vb.net
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
C#
//C#
private bool validateXml(String infile)
{
    //First we create the xmltextreader
    XmlTextReader xmlr = 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
    XmlValidatingReader xmlvread = new XmlValidatingReader(xmlr);

    // Set the validation event handler
    xmlvread.ValidationEventHandler += 
        new ValidationEventHandler (ValidationCallBack);
    m_Success = true; //make sure to reset the success var

    // Read XML data
    while (xmlvread.Read()){}

    //Close the reader.
    xmlvread.Close();

    //The validationeventhandler is the only thing that would set 
    //m_Success to false
    return m_Success;
}

Finally, we have the code to validate the schema (XSD) file directly. As mentioned before, this function has a callback to the same on validation event as the XML validation function did.

Here is the code:

VB
'vb.net
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
C#
//C#
private bool validateSchema(String infilename)
{
    //this function will validate the schema file (xsd)
    XmlSchema myschema; 
    m_Success = true; //make sure to reset the success var
    StreamReader sr = new StreamReader(infilename);
    try
    {
    myschema = XmlSchema.Read(sr, 
        new ValidationEventHandler (ValidationCallBack));
    //This compile statement is what ususally catches the errors
    myschema.Compile(new ValidationEventHandler (ValidationCallBack));
    }                            
        finally
    {
        sr.Close();
    }
    return m_Success;
}

Conclusion

Well, that is it. Not really a lot to it. I am sure many of you already knew how to do this. I kind of wish you had published an article, it would have saved me some time. Still the learning process is always enjoyable and never ends.

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

 
PraiseWish I had this sooner Pin
Joshua Burris12-May-19 19:04
Joshua Burris12-May-19 19:04 
QuestionBlank Fields in XML Pin
Member 1095014216-Jul-14 0:02
Member 1095014216-Jul-14 0:02 
AnswerRe: Blank Fields in XML Pin
kubben16-Jul-14 5:30
kubben16-Jul-14 5:30 
GeneralMy vote of 5 Pin
Roberto M Cedillo Camacho22-Jan-14 5:18
Roberto M Cedillo Camacho22-Jan-14 5:18 
GeneralMy vote of 5 Pin
raiserle6-Nov-12 21:17
raiserle6-Nov-12 21:17 
GeneralValidate XML file Without XSD declaration Pin
PiyushVarma9-Dec-10 9:14
PiyushVarma9-Dec-10 9:14 
GeneralRe: Validate XML file Without XSD declaration Pin
kubben9-Dec-10 9:24
kubben9-Dec-10 9:24 
GeneralRe: Validate XML file Without XSD declaration Pin
PiyushVarma9-Dec-10 14:47
PiyushVarma9-Dec-10 14:47 
Generalvalidating xml with xsd in 2005 framwork 2.0 [modified] Pin
svknair15-Nov-10 21:10
svknair15-Nov-10 21:10 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
kubben16-Nov-10 1:21
kubben16-Nov-10 1:21 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
svknair16-Nov-10 1:53
svknair16-Nov-10 1:53 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
kubben16-Nov-10 1:59
kubben16-Nov-10 1:59 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
svknair16-Nov-10 19:13
svknair16-Nov-10 19:13 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
kubben17-Nov-10 1:36
kubben17-Nov-10 1:36 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
svknair17-Nov-10 18:42
svknair17-Nov-10 18:42 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
kubben18-Nov-10 2:09
kubben18-Nov-10 2:09 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
svknair18-Nov-10 19:05
svknair18-Nov-10 19:05 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
kubben19-Nov-10 2:30
kubben19-Nov-10 2:30 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
svknair2-Dec-10 18:33
svknair2-Dec-10 18:33 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pin
kubben3-Dec-10 0:57
kubben3-Dec-10 0:57 
GeneralMy vote of 1 Pin
chowdary p18-Oct-10 23:24
chowdary p18-Oct-10 23:24 
GeneralMy vote of 1 Pin
ddecoy1-Jul-10 3:42
ddecoy1-Jul-10 3:42 
GeneralMy vote of 1 Pin
Muris Hadzimejlic14-Dec-09 1:52
Muris Hadzimejlic14-Dec-09 1:52 
General[My vote of 2] poor article Pin
Donsw24-Aug-09 6:28
Donsw24-Aug-09 6:28 
GeneralRe: [My vote of 2] poor article Pin
kubben24-Aug-09 6:34
kubben24-Aug-09 6:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.