TechBubbles

Validating XML Document Using XSD in C#.NET

Introduction

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

Create an Document

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

  4.  Save the file as Employee. file 

Create the XSD Schema, and Link to Document

1. Start Visual Studio .NET

2. Create a new empty text file

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

<? 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. file, and link it to the XSD schema as follows
<? 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 as EmployeeWithXSD..

Validate Document

1. Load the EmployeeWithXSD. using XmlTextReader as follows:

XmlTextReader r = new XmlTextReader("C:\\EmployeeWithXSD.");
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  

    document.

1 Comment so far

  1. DotNetKicks.com August 28th, 2008 9:37 pm

    Validating the XML Document using XSD…

    You’ve been kicked (a good thing) - Trackback from DotNetKicks.com…

Leave a reply

Why ask?