Microsoft KB Archive/307379

= How To Validate an XML Document by Using DTD, XDR, or XSD in Visual C# .NET =

Article ID: 307379

Article Last Modified on 12/5/2005

-

APPLIES TO


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

-



This article was previously published under Q307379



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

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Xml
 * System.Xml.Schema

IN THIS TASK
SUMMARY Requirements Create an XML Document Using the DTD
 * Create the DTD, and Link to XML Document
 * Use the DTD to Validate the XML Document

Using the XDR Schema
 * Create the XDR Schema, and Link to XML Document
 * Use the XDR Schema to Validate the XML Document

Using the XSD Schema
 * Create the XSD Schema, and Link to XML Document
 * Use the XSD Schema to Validate the XML Document

Use Namespaces in the XSD Schema Cache Namespaces Verify That It Works



SUMMARY
This article demonstrates how to apply a Document Type Definition (DTD), a Microsoft XML-Data Reduced (XDR) schema, or an XML Schema Definition Language (XSD) schema to an Extensible Markup Language (XML) document. This article also describes how to use the XmlValidatingReader class to validate an XML document against the specified grammar, as well as how to use the XmlSchemaCollection class to cache schemas in memory in order to optimize XML validation.

XML documents contain elements and attributes. They provide a flexible and powerful way to exchange data between applications and organizations. To specify the allowable structure and content of an XML document, you can write a DTD, an XDR schema, or an XSD schema. XSD schemas are the preferred method to specify XML grammars in the Microsoft .NET Framework, but DTDs and XDR schemas are also supported.

back to the top

Requirements
This article assumes that you familiar with the following topics:
 * Microsoft Visual C# .NET or Microsoft Visual Basic .NET syntax
 * XML concepts, including validation issues

back to the top

Create an XML Document
 Start Visual Studio .NET. Create a new XML file on your local computer.  Add the following data to the XML document to represent a product in a catalog:  Rugby jersey   Save the file as Product.xml in a new folder named C:\MyFolder.</ol>

back to the top

Create the DTD, and Link to XML Document
<ol> In Visual Studio .NET, create an empty text file.</li>  Add the following DTD declarations to the file to describe the grammar of the XML document: <!ELEMENT Product (ProductName)> <!ATTLIST Product ProductID CDATA #REQUIRED> <!ELEMENT ProductName (#PCDATA)> </li> Save the file as Product.dtd in the C:\MyFolder directory.</li> Open Product.xml in Visual Studio .NET.</li>  Add the following DOCTYPE statement to the top of Product.xml to link the XML document to the DTD file: <?xml version=&quot;1.0&quot;?> <!DOCTYPE Product SYSTEM &quot;Product.dtd&quot;> </li> Save the modified XML document as ProductWithDTD.xml.</li></ol>

back to the top

Use the DTD to Validate the XML Document
<ol> In Visual Studio .NET, create a new Visual C# Console Application project named ValidateXml.</li>  Add two using statements to the beginning of Class1.cs as follows: using System.Xml;       // for XmlTextReader and XmlValidatingReader using System.Xml.Schema; // for XmlSchemaCollection (which is used later) </li>  In Class1.cs, declare a boolean variable named isValid before the start of the Main method as follows: private static bool isValid = true;     // If a validation error occurs, // set this flag to false in the // validation event handler. </li>  Create an XmlTextReader object to read an XML document from a text file in the Main method, and then create an XmlValidatingReader to validate this XML data as follows: XmlTextReader r = new XmlTextReader(&quot;C:\\MyFolder\\ProductWithDTD.xml&quot;); XmlValidatingReader v = new XmlValidatingReader(r); </li>  The ValidationType property of the XmlValidatingReader object indicates the type of validation that is required (DTD, XDR, or Schema). Set this property to DTD as follows: v.ValidationType = ValidationType.DTD; </li>  If any validation errors occur, the validating reader generates a validation event. Add the following code to register a validation event handler (you will implement the MyValidationEventHandler method in Step 8): v.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler); </li>  Add the following code to read and validate the XML document. If any validation errors occur, MyValidationEventHandler is called to address the error. This method sets isValid to false (see Step 8). You can check the status of isValid after validation to see if the document is valid or invalid. 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(&quot;Document is valid&quot;); else Console.WriteLine(&quot;Document is invalid&quot;); </li>  Write the MyValidationEventHandler method after the Main method as follows: public static void MyValidationEventHandler(object sender,                                            ValidationEventArgs args) {  isValid = false; Console.WriteLine(&quot;Validation event\n&quot; + args.Message); }                   </li> Build and run the application. The application should report that the XML document is valid.</li> In Visual Studio .NET, modify ProductWithDTD.xml to invalidate it (for example, delete the &quot;<ProductName>Rugby jersey</ProductName>&quot; element).</li> <li>Run the application again. You should receive the following error message:

Validation event

Element 'Product' has invalid content. Expected 'ProductName'.

An error occurred at file:///C:/MyFolder/ProductWithDTD.xml(4, 5).

Document is invalid

</li></ol>

back to the top

Create the XDR Schema, and Link to XML Document
<ol> <li>In Visual Studio .NET, create an empty text file.</li> <li> Add the following XDR schema definitions to the file to describe the grammar of the XML document: <?xml version=&quot;1.0&quot;?> <Schema name=&quot;ProductSchema&quot; xmlns=&quot;urn:schemas-microsoft-com:xml-data&quot; xmlns:dt=&quot;urn:schemas-microsoft-com:datatypes&quot;>

<ElementType name=&quot;Product&quot; content=&quot;eltOnly&quot;> <attribute type=&quot;ProductID&quot; required=&quot;yes&quot;/> <element type=&quot;ProductName&quot;/> </ElementType>

<AttributeType name=&quot;ProductID&quot; dt:type=&quot;int&quot;/> <ElementType name=&quot;ProductName&quot; dt:type=&quot;string&quot;/> </Schema> </li> <li>Save the file as Product.xdr in the C:\MyFolder directory.</li> <li> Open the original Product.xml file, and link it to the XDR schema as follows: <?xml version=&quot;1.0&quot;?> <Product ProductID=&quot;123&quot; xmlns=&quot;x-schema:Product.xdr&quot;> <ProductName>Rugby jersey</ProductName> </Product> </li> <li>Save the modified XML document as ProductWithXDR.xml.</li></ol>

back to the top

Use the XDR Schema to Validate the XML Document
<ol> <li> Modify your application so that XmlTextReader loads ProductWithXDR.xml as follows: XmlTextReader r = new XmlTextReader(&quot;C:\\MyFolder\\ProductWithXDR.xml&quot;); </li> <li> Set the ValidationType to XDR so that the validating reader performs XDR validation: v.ValidationType = ValidationType.XDR; </li> <li>Build and run the application. The application should report that the XML document is valid.</li> <li>Modify ProductWithXDR.xml to invalidate it.</li> <li>Build and run the application again. You should receive a validation error.</li></ol>

back to the top

Create the XSD Schema, and Link to XML Document
<ol> <li>In Visual Studio .NET, create an empty text file.</li> <li> Add the following XSD schema definitions to the file to describe the grammar of the XML document: <?xml version=&quot;1.0&quot;?> <xsd:schema xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;> <xsd:element name=&quot;Product&quot;> <xsd:complexType> <xsd:sequence> <xsd:element name=&quot;ProductName&quot; type=&quot;xsd:string&quot;/> </xsd:sequence> <xsd:attribute name=&quot;ProductID&quot; use=&quot;required&quot; type=&quot;xsd:int&quot;/> </xsd:complexType> </xsd:element> </xsd:schema> </li> <li>Save the file as Product.xsd in the C:\MyFolder directory.</li> <li> Open the original Product.xml, and link it to the XSD schema as follows: <?xml version=&quot;1.0&quot;?> <Product ProductID=&quot;123&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:noNamespaceSchemaLocation=&quot;Product.xsd&quot;> <ProductName>Rugby jersey</ProductName> </Product> </li> <li>Save the modified XML document as ProductWithXSD.xml.</li></ol>

back to the top

Use the XSD Schema to Validate the XML Document
<ol> <li> Modify your application so that XmlTextReader loads ProductWithXSD.xml as follows: XmlTextReader r = new XmlTextReader(&quot;C:\\MyFolder\\ProductWithXSD.xml&quot;); </li> <li> Set the ValidationType to Schema so that the validating reader performs XSD schema validation: v.ValidationType = ValidationType.Schema; </li> <li>Build and run the application to use the XSD schema to validate the XML document.</li></ol>

back to the top

Use Namespaces in the XSD Schema
<ol> <li>In Visual Studio .NET, open ProductWithXSD.xml.</li> <li> Declare a default namespace urn:MyNamespace in the document. In addition, modify the XSD link so that it specifies the XSD schema to validate content in this namespace: <?xml version=&quot;1.0&quot;?> <Product ProductID=&quot;123&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns=&quot;urn:MyNamespace&quot; xsi:schemaLocation=&quot;urn:MyNamespace Product.xsd&quot;> <ProductName>Rugby jersey</ProductName> </Product> </li> <li>Save your changes to ProductWithXSD.xml.</li> <li> Open Product.xsd. Modify the <xsd:schema> start tag as follows so that the schema applies to the namespace urn:MyNamespace: <xsd:schema xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot; targetNamespace=&quot;urn:MyNamespace&quot; elementFormDefault=&quot;qualified&quot;> </li> <li>Save your changes to Product.xsd.</li> <li>Build and run the application to use the XSD schema to validate the XML document.</li></ol>

back to the top

Cache Namespaces
<ol> <li> In Visual Studio .NET, open Class1.cs. Create an XmlSchemaCollection object at the beginning of the Main method as follows: XmlSchemaCollection cache = new XmlSchemaCollection; </li> <li> The XmlSchemaCollection object allows you to cache schemas in memory for improved performance. Each schema is associated with a different namespace. Add the following code to cache Product.xsd: cache.Add(&quot;urn:MyNamespace&quot;, &quot;C:\\MyFolder\\Product.xsd&quot;); </li> <li> Add the following statement after the code that creates the XmlValidatingReader object to add the schema cache to XmlValidatingReader so that the reader can use the in-memory schemas: v.Schemas.Add(cache); </li></ol>

back to the top

Verify That It Works

 * 1) Build and then run the application.
 * 2) Verify that the XML document is still validated against the XSD schema.
 * 3) Modify the ProductWithXSD.xml to invalidate it.
 * 4) Verify that the application detects these validation errors.

back to the top

Keywords: kbhowtomaster KB307379

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.