Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 26 May 2005
Rate this:
Please Sign up or sign in to vote.
This article is about XML and XSD validation.

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.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#
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 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.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#
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.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#
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)

Share

About the Author

kubben
Web Developer
United States United States
I started my programmer career over 18 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 both vb.net and C#. Lately I have been using VS2012 and writing a Windows 8 app. You can search for the app it is called ConvertIT.
 
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

 
QuestionBlank Fields in XML PinmemberMember 1095014216-Jul-14 0:02 
AnswerRe: Blank Fields in XML Pinmemberkubben16-Jul-14 5:30 
GeneralMy vote of 5 PinmemberRoberto M Cedillo Camacho22-Jan-14 5:18 
GeneralMy vote of 5 Pinmemberraiserle6-Nov-12 21:17 
GeneralValidate XML file Without XSD declaration PinmemberPiyushVarma9-Dec-10 9:14 
GeneralRe: Validate XML file Without XSD declaration Pinmemberkubben9-Dec-10 9:24 
Here is a sample of some simple C# code that works in .net 2.0:
 
private void Form1_Load(object sender, EventArgs e)
{
XmlDocument tmpDoc = new XmlDocument();
tmpDoc.Load(@"Sample.xml");
tmpDoc.Schemas.Add(null, @"Sample.xsd");
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
 
tmpDoc.Validate(eventHandler);
 
}
 
static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
MessageBox.Show("Error: {0}"+ e.Message);
break;
case XmlSeverityType.Warning:
MessageBox.Show("Warning {0}"+ e.Message);
break;
}
 
}
 
Hope that helps.
 
Ben
GeneralRe: Validate XML file Without XSD declaration PinmemberPiyushVarma9-Dec-10 14:47 
Generalvalidating xml with xsd in 2005 framwork 2.0 [modified] Pinmembersvknair15-Nov-10 21:10 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmemberkubben16-Nov-10 1:21 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmembersvknair16-Nov-10 1:53 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmemberkubben16-Nov-10 1:59 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmembersvknair16-Nov-10 19:13 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmemberkubben17-Nov-10 1:36 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmembersvknair17-Nov-10 18:42 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmemberkubben18-Nov-10 2:09 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmembersvknair18-Nov-10 19:05 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmemberkubben19-Nov-10 2:30 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmembersvknair2-Dec-10 18:33 
GeneralRe: validating xml with xsd in 2005 framwork 2.0 Pinmemberkubben3-Dec-10 0:57 
GeneralMy vote of 1 Pinmemberchowdary p18-Oct-10 23:24 
GeneralMy vote of 1 Pinmemberddecoy1-Jul-10 3:42 
GeneralMy vote of 1 PinmemberMuris Hadzimejlic14-Dec-09 1:52 
General[My vote of 2] poor article PinmemberDonsw24-Aug-09 6:28 
GeneralRe: [My vote of 2] poor article Pinmemberkubben24-Aug-09 6:34 
GeneralMy vote of 1 PinmemberParesh Gheewala2-Dec-08 19:58 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 26 May 2005
Article Copyright 2005 by kubben
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid