Validation of XML with XSD

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

  • 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=http://rxhealth.pw ] generic viagra uk suppliers [/url] read additional Erectile Dysfunction Treatment - Finding a Therapy That Works For You

    Reply
  • 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=http://www.hollistercoefrance.fr]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=http://www.airjordanfrpascherz.com]air jordan[/url] times de la classique, un mythe, une epoque! Francais de chaussures Louboutin meilleure [url=http://www.abercrombieafranceusolde.fr]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=http://www.hollisteruonlineshops.de]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=http://www.hollisterfranceamagesin.fr]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=http://www.abercrombiexandfitchukes.co.uk]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=http://www.abercrombiesdeutschlandshopu.com]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=http://www.abercrombiesdeutschlandshopu.com]abercrombie deutschland[/url] pauvres decorous des organisations caritatives.

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

    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
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • On-demand Event Event Date: September 17, 2014 Another day, another end-of-support deadline. You've heard enough about the hazards of not migrating to Windows Server 2008 or 2012. What you may not know is that there's plenty in it for you and your business, like increased automation and performance, time-saving technical features, and a lower total cost of ownership. Check out this webcast and join Rich Holmes, Pomeroy's practice director of virtualization, as he discusses the future state of your servers, …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds