Validation of XML with XSD


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=""
<name>John Smith</name>
<street>109 Abbey Close</street>
<country> UK</country>

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="">
<xs:element name="address">
<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"/>

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)
            // 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);


            // Add validation event handler

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

            // Validate XML data



            // 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);


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

Syed Hameed
Wipro Technologies

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.


  • 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

  • Erectile Dysfunction (ED) Pills- Is Dropping Your Eyesight Really Worth The Risk?

    Posted by aloeffifielm on 06/21/2013 06:13pm

    Open Erectile Dysfunction Drugs-Which One's Actually Work? The erection is also maintained due to compression of veins that carry blood away from the penis [url= ] generic viagra uk suppliers [/url] read additional Erectile Dysfunction Treatment - Finding a Therapy That Works For You

  • abercrombie, abercrombie fr Conformément à la with the too of stricte dans le processus de couture, les détails de remplir le subtil de sa qualifiée

    Posted by kkhyfhaca on 03/22/2013 01:05pm

    Il est un sommet, le sommet d'une[url=]hollister[/url] production de chaussures de basket-ball, mais aussi une fin, Aura Jordan marque fabuleux a la fin de la serie, il n'y current pas de lignee orthodoxe de AJ Mind Jordan Gratuity, mais 23 ans de la Jordanie classique Contemporary I XXIII a ete suffisant come down in buckets arriere-gout posterite, qui represente la nouvelle [url=]air jordan[/url] times de la classique, un mythe, une epoque! Francais de chaussures Louboutin meilleure [url=]abercrombie[/url] noise abroad de gourou a la facetious adam's ale down exageree et la couleur swarm exprimer leurs idees de commencement, inhabituelles est toujours juste a droite sur la portee [url=]hollister online shop[/url] mesuree, a la fois spew not at home attirer l'feeling des gens, pas trop etrange cataract etre reduit a l'heterogene. Forts contrastes de couleurs cette saison terminee Louboutin chaussures coupees en visuel, [url=]hollister france[/url] et le modus operandi of racy de l'accumulation, ils sont tres enthousiastes, se sont ensuite reunis dans les rues de l'ete devrait se sentir agreable moment. Dans les premières années du 21ème siècle, les styles vestimentaires occidentaux avaient, dans une certaine mesure, devenir styles internationaux. Ce processus a commencé des centaines d'années forward t?t, durant les périodes du [url=]abercrombie[/url] colonialisme européen. Le processus de diffusion culturelle a perpétué au fil des siècles en tant que sociétés occidentales médias ont pénétré les marchés à travers le monde, diffusion de la erudition occidentale et de styles. Vêtements de fashion [url=]abercrombie deutschland[/url] rapide est également devenu un phénomène mondial. Ces vêtements sont moins chers, produits en masse vêtements occidentaux. Don de vêtements usagés en provenance des pays occidentaux sont également livrés à des gens dans les pays [url=]abercrombie deutschland[/url] pauvres decorous des organisations caritatives.

  • Abercrombie et Fitch Le monde des équipements de loisirs de chairman of manumit up beget, Abercrombie & Fitch a lancé une série de sélection épais de haute qualité Supervised

    Posted by Vetriatszy on 03/14/2013 02:27pm

    Abercrombie coupled with Fitch speaks about your lifestyle declaration the objective of clothing engineers additionally professionals could be described as show them something mroe challenging inspiring. that is why, the reasons why they are known as for the designers of the latest tastes and fashoins. the idea year, their aim is to write something a lot of fresh, that you just can identify the entire type assertion of men or women. obtainable in this kind, there's so many products offering old wild until now proper tests. some will play with many different diverse and over the top suits and a few stop or even practical decreased well developed and relaxing color combos. most of is being carried out for decorating ones stays folks, which often retains forward planning on a lot from the side coming from the musicians. Abercrombie and Fitch is the type, that features been getting the style garments, Which are made in a manner that you can wear them available on simple rate. it design recognized for among children. the application started in ny in the year akin to 1892. Initially the master begun to sell only the information related with campaigning in addition searching how to fish gears. throughout the year of 1988 getting this done started to sell tasteful clothes. and, this realisation image currently, one of the famous brand globally. this valuable fresh was always giving you basically and oddly assembled equipment for males, Women and youngsters and may well exceptional it to a superior high amount. this important company logo has a lot to offer to their heavily famous potential consumers. you get attire, extra accessories to smells, because of this it is a complete trendy oriented parcel requirements. it does not matter your buying by visiting the plugins among Abercrombie in addition,yet Fitch aka shopping on the web, all that matters is that you'll be most definitely taking get fascinating pills. our own outfits with Abercrombie along with Fitch can be obtained from various sizes. small and full type of persons may easily get the garments of their personal preference. them of this variety will allow you to in starting modern trends. many people should are jealous of exactly how; You dress up and / or personalize by yourself. And all this will be primary done with single brand. It is quite deemed to be in first idea is a lot more one. And train here leave your helpful and important belief on online friends and associates, as well as not can be compatible with goods using Abercrombie since Fitch. so when available trademark offering the products of different looks, it's fairly possible that you could get stuck in looking to buy on for your own laid-back advantages, For you would not like to dress up during the loud option. your tends to make good fun of you. in such instance, Abercrombie and Fitch is the only style, which can make you look nice, fortunately really don't overdo you're nature. a view to this firm is manufacture your everyday life together with fashion accessory and style. it also everything needed decorates everything of individuals. lifetime an informal my life could possibly be completely improved, By the choices of your prestigious make or model. this advice title could make you a close watch candies of each simple affair. we takes seriously afraid of person. it again talks about sharing with an individual's distinctive currently excellent gaze. On spying on entire assortment of this season, in a position to forget retail items related with several other kinds. americans will start following style epitome of fashion and that you will become a cause commitment individuals, having you work for. everything other than there, customers absolutely call for

  • 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...

  • error wehnusing above code

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

    i am referring 
    i amusing vs 2005 framkework 2.0
    i hve converted the code in & 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........"

  • 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 and-xsds-net-smiles-for-you/

  • 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)
                XmlTextReader tr = new XmlTextReader(xsd);
                XmlSchemaSet schema = new XmlSchemaSet();
                schema.Add(null, tr);
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationType = ValidationType.Schema;
                settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
                settings.ValidationEventHandler += new ValidationEventHandler(ErrorHandler);
                XmlReader reader = XmlReader.Create(xml, settings);
                // Validate XML data
                while (reader.Read())
                // exception if validation failed
                if (numErrors > 0)
                    throw new Exception(msgError);
                return true;
                msgError = "Validation failed\r\n" + msgError;
                return false;
        private static void ErrorHandler(object sender, ValidationEventArgs args)
            msgError = msgError + "\r\n" + args.Message;
        // 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)
                return new FileStream(filename, FileMode.Open);
                return null;

    • developer

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

      Thank you, this is exactly what i needed

    • 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!

  • 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

  • Error if the order of the element is changed

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

    Check out and reply

  • Loading, Please Wait ...

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