TechBubbles Microsoft Technology BLOG

Validating XML Document Using XSD in C#.NET


This post explains how to apply  XML Schema Definition Language(XSD) to Extensible Markup Language (XML) document. Basics of XSD.

Create an XML Document

  1. Start Visual Studio .NET
  2. Create a new XML File.
  3. Add the following data to the XML Document
<Employee EmployeeID="123">
   <EmployeeName>James Bond</EmployeeName>

  4.  Save the file as Employee.xml file 

Create the XSD Schema, and Link to XML Document

1. Start Visual Studio .NET

2. Create a new empty text file

3. Add the following XSD Schema definitions to describe the XML document.

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="">
   <xsd:element name="Employee">
            <xsd:element name="EmployeeName" type="xsd:string"/>
         <xsd:attribute name="EmployeeID" use="required" type="xsd:int"/>

4. Save the file as Employee.xsd 
5. Open the original Employee.xml file, and link it to the XSD schema as follows
<?xml version="1.0"?>
<Employee EmployeeID="123" 
   <EmployeeName>Rugby jersey</EmployeeName>

6. Save the modified xml as EmployeeWithXSD.xml.

Validate XML Document

1. Load the EmployeeWithXSD.xml using XmlTextReader as follows:

XmlTextReader r = new XmlTextReader("C:\\EmployeeWithXSD.xml");
XmlValidatingReader v = new XmlValidatingReader(r);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler += 
   new ValidationEventHandler(MyValidationEventHandler);
while (v.Read())
   // Can add code here to process the content.

// Check whether the document is valid or invalid.
if (isValid)
   Console.WriteLine("Document is valid");
   Console.WriteLine("Document is invalid");
public static void MyValidationEventHandler(object sender, 
                                            ValidationEventArgs args) 
   isValid = false;
   Console.WriteLine("Validation event\n" + args.Message);

2. Build and run the application to use the XSD schema to validate the XML 


About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.


TechBubbles Microsoft Technology BLOG

Follow me


Tag Cloud