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:
- The ValidationHandler event handler method is defined.
- The XSD schema is being parsed using XmlTextReader class.
- The parsed schema is added to the schema collection using XmlSchemaCollection class.
- The schema collection is associated with XmlValidatingReader class.
- The event handler method is associated with XmlValidatingReader class.
- 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

Comments
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:05pmIl 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.
ReplyAbercrombie 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:27pmAbercrombie 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
ReplyCustomize error messages
Posted by Jportelas on 07/07/2011 10:17amIs 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...
Replyerror wehnusing above code
Posted by svibuk on 11/15/2010 04:04amCreating a xml using xsd and c#
Posted by stjhimy on 10/18/2009 05:51pmHere'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/
ReplyVS2005 version
Posted by FTWinston on 07/25/2008 06:05amI'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; } } }-
-
Replydeveloper
Posted by alena on 05/25/2012 11:03amThank you, this is exactly what i needed
ReplyCould not find schema information for the element 'EPIAccountOpeningResponse'.
Posted by dchen on 10/13/2008 12:16amHi, 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!
ReplyHow to Display Multiple Errors?
Posted by mouthpiec on 04/21/2008 08:43amIs 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
ReplyError if the order of the element is changed
Posted by krishnaveni on 05/20/2006 07:14amCheck out and reply
ReplyGreat example, can you update for VS2005?
Posted by dougatevalto on 01/05/2006 02:20pmThere 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!
-
ReplyUpdate version for VS2005
Posted by mouthpiec on 04/20/2008 08:08amDid you managed to get an updated version for VS2005? if so can you please send me a copy?
Reply? urlpath ?
Posted by rdevalco on 01/13/2005 10:33am-
Replyhave you solved this problem?
Posted by mouthpiec on 04/20/2008 08:06amhave you solved this problem? because right now I have the same problem
Reply