TechBubbles Microsoft Technology BLOG

Validating XML Document Using XSD in C#.NET

Introduction

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>
</Employee>

  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="http://www.w3.org/2001/XMLSchema">
   <xsd:element name="Employee">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="EmployeeName" type="xsd:string"/>
         </xsd:sequence>
         <xsd:attribute name="EmployeeID" use="required" type="xsd:int"/>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>

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" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="Employee.xsd">
   <EmployeeName>Rugby jersey</EmployeeName>
</Employee>

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.
}
v.Close();

// Check whether the document is valid or invalid.
if (isValid)
   Console.WriteLine("Document is valid");
else
   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 

    document.

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.

4 Comments

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud