HOW TO: Validate XML Fragments Against an XML Schema in Visual C#.NET

For a Microsoft Visual Basic .NET version of this article, see 317463 .



This step-by-step article describes how to use XmlValidatingReader and XMLSchemaCollection objects to validate an Extensible Markup Language (XML) fragment against an XML schema.

XmlValidatingReader implements the XmlReader class and provides support for XML data validation. The Schemas property of XmlValidatingReader connects the reader to the schema files cached in an XmlSchemaCollection. The ValidationType property of XmlValidatingReader specifies the type of validation the reader should perform. If you set the property to ValidationType.None, you create a nonvalidating reader.

You can only add XML Schema Definition Language (XSD) schemas and XML-Data Reduced (XDR) schemas to XmlSchemaCollection. Use the Add method with a namespace URI to load schemas. For XML schemas, the typical namespace URI is the targetNamespace property of the schema.


The following list outlines the recommended hardware, software, network infrastructure, and service packs that you will need:
  • Microsoft Visual Studio .NET installed on a compatible Microsoft Windows operating system
This article assumes that you are familiar with the following topics:
  • Visual C# .NET
  • Basic XML standards
  • XSD schemas

Create an XSD Schema

Paste the following code in a new text file named C:\Books.xsd:
<xsd:schema xmlns:xsd="" xmlns="urn:bookstore-schema" elementFormDefault="qualified" targetNamespace="urn:bookstore-schema">
<xsd:element name="bookstore" type="bookstoreType" />
<xsd:element name="comment" type="xsd:string" />
<xsd:element name="author" type="authorName"/>
<xsd:complexType name="authorName">
<xsd:element name="first-name" type="xsd:string" />
<xsd:element name="last-name" type="xsd:string" />
<xsd:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="book" type="bookType" />
<xsd:element ref="comment" minOccurs="0" />
<xsd:complexType name="bookType">
<xsd:element name="title" type="xsd:string" />
<xsd:element ref="author" />
<xsd:element name="price" type="xsd:decimal" />
<xsd:attribute name="genre" type="xsd:string" />


Create a Visual C# .NET Application

  1. Create a new Visual C# .NET Console application.
  2. Replace the code in Class1.cs with the following code:
    using System;
    using System.Xml;
    using System.Xml.Schema;

    namespace ConsoleApplication3
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class Class1
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    System.Boolean m_success;

    static void Main(string[] args)
    // TODO: Add code to start application here.
    XmlValidatingReader reader = null;
    XmlSchemaCollection myschema = new XmlSchemaCollection();
    ValidationEventHandler eventHandler = new ValidationEventHandler(Class1.ShowCompileErrors );

    //Create the XML fragment to be parsed.
    String xmlFrag = "<author xmlns='urn:bookstore-schema' xmlns:xsi=''>" +
    "<first-name>Herman</first-name>" +
    "<last-name>Melville</last-name>" +

    //Create the XmlParserContext.
    XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

    //Implement the reader.
    reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
    //Add the schema.
    myschema.Add("urn:bookstore-schema", "c:\\Books.xsd");

    //Set the schema type and add the schema to the reader.
    reader.ValidationType = ValidationType.Schema;

    while (reader.Read())

    Console.WriteLine("Completed validating xmlfragment");
    catch (XmlException XmlExp)
    catch(XmlSchemaException XmlSchExp)
    catch(Exception GenExp)

    public static void ShowCompileErrors(object sender, ValidationEventArgs args)
    Console.WriteLine("Validation Error: {0}", args.Message);

  3. When the following message is displayed in the output window, the XML fragment is a valid element:

    Completed validating xmlfragment
NOTE: Only the type declarations and the top-level elements in the XML schema are validated against an XML schema. Subelements are considered as local and therefore cannot be validated. In order to validate a subelement, declare a top-level element and refer to that.


For additional information, click the article numbers below to view the articles in the Microsoft Knowledge Base:

307379 HOW TO: Validate an XML Document by Using DTD, XDR, or XSD in Visual C# .NET
313826 INFO: Roadmap for XML Schemas in the .NET Framework
313651 INFO: Roadmap for XML in the .NET Framework
For additional information, see the following MSDN Web sites:

Article ID: 318504 - Last Review: Mar 23, 2009 - Revision: 1