Microsoft KB Archive/318504

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

Article ID: 318504

Article Last Modified on 9/16/2003

-

APPLIES TO


 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft .NET Framework 1.0
 * Microsoft .NET Framework 1.1

-



This article was previously published under Q318504



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

IN THIS TASK
SUMMARY
 * Requirements
 * Create an XSD Schema
 * Create a Visual C# .NET Application

REFERENCES



SUMMARY
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.

back to the top

Requirements
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

back to the top

Create an XSD Schema
Paste the following code in a new text file named C:\Books.xsd:              <xsd:element ref=&quot;comment&quot; minOccurs=&quot;0&quot; /> </xsd:sequence> </xsd:complexType> <xsd:complexType name=&quot;bookType&quot;>  <xsd:element name=&quot;title&quot; type=&quot;xsd:string&quot; /> <xsd:element ref=&quot;author&quot; /> <xsd:element name=&quot;price&quot; type=&quot;xsd:decimal&quot; /> </xsd:sequence> <xsd:attribute name=&quot;genre&quot; type=&quot;xsd:string&quot; /> </xsd:complexType> </xsd:schema> back to the top

Create a Visual C# .NET Application
<ol> <li>Create a new Visual C# .NET Console application.</li> <li> Replace the code in Class1.cs with the following code: using System; using System.Xml; using System.Xml.Schema;

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

[STAThread] 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 );

try {               //Create the XML fragment to be parsed. String xmlFrag = &quot;<author xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>&quot; + &quot;<first-name>Herman</first-name>&quot; + &quot;<last-name>Melville</last-name>&quot; + &quot; &quot;;

//Create the XmlParserContext. XmlParserContext context = new XmlParserContext(null, null, &quot;&quot;, XmlSpace.None); //Implement the reader. reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context); //Add the schema. myschema.Add(&quot;urn:bookstore-schema&quot;, &quot;c:\\Books.xsd&quot;);

//Set the schema type and add the schema to the reader. reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(myschema);

while (reader.Read) {               }                Console.WriteLine(&quot;Completed validating xmlfragment&quot;); }           catch (XmlException XmlExp) {               Console.WriteLine(XmlExp.Message); }           catch(XmlSchemaException XmlSchExp) {               Console.WriteLine(XmlSchExp.Message); }           catch(Exception GenExp) {               Console.WriteLine(GenExp.Message); }           finally {               Console.Read; }

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

} }                   </li> <li> When the following message is displayed in the output window, the XML fragment is a valid element: <pre class="fixed_text">Completed validating xmlfragment </li></ol>

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.

back to the top

<div class="references_section">