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
Customize 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; } } }-
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