Validation of XML with XSD

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

Introduction

This article explains about how to validate an XML document with XSD schema. The validation is performed by checking whether the XML document is a well-formed one by programmatically using .NET classes in C#.

XML document

An XML document contains elements, attributes, and values of primitive data types. For example, consider the following XML document:

<address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="address.xsd"> 
<name>John Smith</name>
<street>109 Abbey Close</street>
<city>Hayes</city>
<country> UK</country>
</address>

XSD schema

XSD schema defines elements, attributes, and the relationship between them. It conforms to the W3C XML schema standards and recommendations. XSD schema for the above XML document, address.xsd, can be given as follows:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="street" type="xs:string"/>
<xs:element name="city"type="xs:string"/>
<xs:element name="country"type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Validation event handler

The ValidationEventHandler event is used to define an event handler for receiving the notification about XSD schema validation errors. The validation errors and warnings are reported through the ValidationEventHandler call-back function. If any validation error occurs, an exception is thrown, and the XmlValidatingReader cannot be restarted.

XML validation with .NET classes

Microsoft .NET framework classes support the W3C XML schema recommendation. The classes used to validate the XML document are XmlTextReader, XmlSchemaCollection, and XmlValidatingReader. The sequence of steps to validate an XML document is given as follows:

  1. The ValidationHandler event handler method is defined.
  2. The XSD schema is being parsed using XmlTextReader class.
  3. The parsed schema is added to the schema collection using XmlSchemaCollection class.
  4. The schema collection is associated with XmlValidatingReader class.
  5. The event handler method is associated with XmlValidatingReader class.
  6. XmlValidatingReader class validates the XML document using the namespace URI specified when the schema was added to the collection.

Sample Code

The following example shows how to validate XML document against XSD schema by using Microsoft .NET framework classes.

using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;

public class XMLValidator
{
    // Validation Error Count
    static int ErrorsCount = 0;

     // Validation Error Message
    static string ErrorMessage = "";

    public static void ValidationHandler(object sender,
                                         ValidationEventArgs args)
    {
        ErrorMessage = ErrorMessage + args.Message + "\r\n";
        ErrorsCount ++;
    }

    public void Validate(string strXMLDoc)
    {
        try
        {
            // Declare local objects
            XmlTextReader         tr   = null;
            XmlSchemaCollection   xsc  = null;
            XmlValidatingReader   vr   = null;

            // Text reader object
            tr  = new XmlTextReader(urlpath);
            xsc = new XmlSchemaCollection();
            xsc.Add(null, tr);

            // XML validator object

            vr = new XmlValidatingReader( strXMLDoc,
                         XmlNodeType.Document, null);

            vr.Schemas.Add(xsc);

            // Add validation event handler

            vr.ValidationType = ValidationType.Schema;
            vr.ValidationEventHandler +=
                     new ValidationEventHandler(ValidationHandler);

            // Validate XML data

            while(vr.Read());

            vr.Close();

            // Raise exception, if XML validation fails
            if (ErrorsCount > 0)
            {
                throw new Exception(ErrorMessage);
            }

            // XML Validation succeeded
            Console.WriteLine("XML validation succeeded.\r\n");
        }
        catch(Exception error)
        {
            // XML Validation failed
            Console.WriteLine("XML validation failed." + "\r\n" +
            "Error Message: " + error.Message);
        }
    }
}

Conclusion

This article explained about the XML document, XSD schema, and how to validate XML document against XSD schema using Microsoft .NET framework classes.

Author:
Syed Hameed
Wipro Technologies
Bangalore



About the Author

Syed Hameed

The author is working for Accenture. He has more than 6 years of experience in Microsoft solution design and development. Some of his major clients are IBM, Caterpillar Inc, Ford Motor Company, Borg warner Automatives, Litton Loan Servicing, Barwil Shipping Corporation, Marks and Spencer.

Comments

  • Always Error

    Posted by Kejvi on 08/03/2016 03:02pm

    str1234str1234123 XML Validation Failed. Error Message: data at the root level is invalid, Line 1, position 1

    Reply
  • Customize error messages

    Posted by Jportelas on 07/07/2011 10:17am

    Is there a way to customize error messages? I mean, we'd like to return user friendly messages to the user when validating XML against XSD, like when the pattern is broken...

    Reply
  • error wehnusing above code

    Posted by svibuk on 11/15/2010 04:04am

    i am referring 
    
    http://www.codeguru.com/csharp/csharp/cs_data/xml/article.php/c6737
    
    i amusing vs 2005 framkework 2.0 v.net
    
    i hve converted the code in vb.net & using 
    
    i need to validate a given xml file against a given xsd
    
    but i am getting some errors
    
    i have created a aspx page & used the code given in the above link
    
    
    
    
    Public Sub Validate(ByVal strXMLDoc As String)
    "sub validate shadows an override method......................."
    
     
    
    
    Dim xsc As XmlSchemaCollection = Nothing
    
    "XmlSchemaCollection is obsolete"
    
    
    
    Dim vr As XmlValidatingReader = Nothing
    
    
    XmlValidatingReader is obsolete use XML READER........"

    Reply
  • Creating a xml using xsd and c#

    Posted by stjhimy on 10/18/2009 05:51pm

    Here's a good tutorial about how to create the xml: Here's a good tutorial about how to create the xml http://www.stjhimy.com/2009/10/17/playing-around-with-xmls- and-xsds-net-smiles-for-you/

    Reply
  • VS2005 version

    Posted by FTWinston on 07/25/2008 06:05am

    I've modified this slightly to better suit my own requirements, but essentially its a VS2005 / .NET 2 version of the above, but it now accepts a stream or a file as parameters for the XML and the XSD.
    
    // call Validate to validate an xml file/stream against an xsd file/stream
    // returns true if valid, false otherwise. GetError will return
    // any error messages taht were produced in the last validation
    public static class XML_XSD_Validator
    {
        static int numErrors = 0;
        static string msgError = "";
    
        public static bool Validate(Stream xml, string xsdFilename)
        {
            return Validate(xml, GetFileStream(xsdFilename));
        }
        public static bool Validate(string xmlFilename, Stream xsd)
        {
            return Validate(GetFileStream(xmlFilename), xsd);
        }
        public static bool Validate(string xmlFilename, string xsdFilename)
        {
            return Validate(GetFileStream(xmlFilename), GetFileStream(xsdFilename));
        }
        public static bool Validate(Stream xml, Stream xsd)
        {
            ClearErrorMessage();
            try
            {
                XmlTextReader tr = new XmlTextReader(xsd);
                XmlSchemaSet schema = new XmlSchemaSet();
                schema.Add(null, tr);
    
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas.Add(schema);
                settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
                settings.ValidationEventHandler += new ValidationEventHandler(ErrorHandler);
                XmlReader reader = XmlReader.Create(xml, settings);
    
                // Validate XML data
                while (reader.Read())
                    ;
                reader.Close();
    
                // exception if validation failed
                if (numErrors > 0)
                    throw new Exception(msgError);
    
                return true;
            }
            catch
            {
                msgError = "Validation failed\r\n" + msgError;
                return false;
            }
        }
    
        private static void ErrorHandler(object sender, ValidationEventArgs args)
        {
            msgError = msgError + "\r\n" + args.Message;
            numErrors++;
        }
    
        // if a validation error occurred, this will return the message
        public static string GetError()
        {
            return msgError;
        }
        
        private static void ClearErrorMessage()
        {
            msgError = "";
            numErrors = 0;
        }
    
        // returns a stream of the contents of the given filename
        private static Stream GetFileStream(string filename)
        {
            try
            {
                return new FileStream(filename, FileMode.Open);
            }
            catch
            {
                return null;
            }
        }
    }

    • developer

      Posted by alena on 05/25/2012 11:03am

      Thank you, this is exactly what i needed

      Reply
    • Could not find schema information for the element 'EPIAccountOpeningResponse'.

      Posted by dchen on 10/13/2008 12:16am

      Hi, I have the following schema declaration in my XSD: with the following sample XML: OP A1234 testing ACC12334 abc When I ran the codes above, error as shown in this Title. Would be much appreciated if you can help. thanks!

      Reply
    Reply
  • How to Display Multiple Errors?

    Posted by mouthpiec on 04/21/2008 08:43am

    Is it possible to modify the code to show all the errors, if more than one error occur? and thanks for the code, it is very useful

    Reply
  • Error if the order of the element is changed

    Posted by krishnaveni on 05/20/2006 07:14am

    Check out and reply

    Reply
  • Great example, can you update for VS2005?

    Posted by dougatevalto on 01/05/2006 02:20pm

    There were a bunch of warning about obsolete methods: Warning 1 'System.Xml.Schema.XmlSchemaCollection' is obsolete: 'Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202' C:\Documents and Settings\Administrator\Local Settings\Application Data\Temporary Projects\XMLValidator\Form1.cs 48 17 XMLValidator Warning 2 'System.Xml.XmlValidatingReader' is obsolete: 'Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead. http://go.microsoft.com/fwlink/?linkid=14202' C:\Documents and Settings\Administrator\Local Settings\Application Data\Temporary Projects\XMLValidator\Form1.cs 50 17 XMLValidator Warning 3 'System.Xml.Schema.XmlSchemaCollection' is obsolete: 'Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202' C:\Documents and Settings\Administrator\Local Settings\Application Data\Temporary Projects\XMLValidator\Form1.cs 55 27 XMLValidator Warning 4 'System.Xml.XmlValidatingReader' is obsolete: 'Use XmlReader created by XmlReader.Create() method using appropriate XmlReaderSettings instead. http://go.microsoft.com/fwlink/?linkid=14202' C:\Documents and Settings\Administrator\Local Settings\Application Data\Temporary Projects\XMLValidator\Form1.cs 60 26 XMLValidator Thanks!

    • Update version for VS2005

      Posted by mouthpiec on 04/20/2008 08:08am

      Did you managed to get an updated version for VS2005? if so can you please send me a copy?

      Reply
    Reply
  • ? urlpath ?

    Posted by rdevalco on 01/13/2005 10:33am

    tr  = new XmlTextReader(urlpath);
    
    relate to the element in your xml schema please (a comment would have been handy)

    • have you solved this problem?

      Posted by mouthpiec on 04/20/2008 08:06am

      have you solved this problem? because right now I have the same problem

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date