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 


Leave a reply

Why ask?