Microsoft KB Archive/315533

= How to validate an XML document by using DTD, XDR, or XSD in Visual Basic =

Article ID: 315533

Article Last Modified on 12/6/2006

-

APPLIES TO


 * Microsoft .NET Framework Class Libraries 1.1
 * Microsoft .NET Framework Class Libraries 1.0
 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-



This article was previously published under Q315533





For a Microsoft Visual C# .NET version of this article, see 307379.



For a Microsoft Visual Basic 6.0 version of this article, see 309616.

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



SUMMARY
Extensible Markup Language (XML) documents contain elements and attributes, and 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 Document Type Definition (DTD), a Microsoft XML-Data Reduced (XDR) schema, or an XML Schema definition language (XSD) schema.

XSD schemas are the preferred way to specify XML grammars in the .NET Framework, but DTDs and XDR schemas are also supported.

In this article, you will learn how to apply a DTD, an XDR schema, or an XSD schema to an XML document in Microsoft Visual Basic 2005 or in Microsoft Visual Basic .NET. You will then learn how to use the XmlValidatingReader class to validate an XML document against the specified grammar. You will also learn how to use the XmlSchemaCollection class to cache schemas in memory as a way to optimize XML validation.

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Visual Basic 2005 or Microsoft Visual Basic .NET

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

Create an XML document
 Start Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET. Then, create a new XML file (on the File menu, point to New, and then click File). Select the XML File type, and then click Open.  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 folder that you will be able to readily access later (the code samples in this article assume a folder named C:\MyFolder).</li></ol>

Create a DTD and link to the XML document
<ol> In Visual Studio 2005 or in Visual Studio .NET, point to New on the File menu, and then click File.</li> Select the Text File type, and then click Open.</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 same folder as your XML document.</li>  Reopen Product.xml in Visual Studio 2005 or in Visual Studio .NET; to do this, point to Open on the File menu, and then click File. Add a DOCTYPE statement (below the &quot;?xml version=&quot;1.0&quot; line), as follows. This links the XML document to the DTD file). <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?> <!DOCTYPE Product SYSTEM &quot;Product.dtd&quot;>                    </li> Save the modified XML document as ProductWithDTD.xml .</li></ol>

Perform validation by using a DTD
<ol> In Visual Studio 2005 or in Visual Studio .NET, create a new Visual Basic Console Application project named ValidateXmlUsingVB.</li>  Visual Studio 2005 or Visual Studio .NET displays a new file named Module1.vb. At the beginning of this file, add two Imports statements, as follows: Imports System.Xml         ' For XmlTextReader and XmlValidatingReader Imports System.Xml.Schema  ' For XmlSchemaCollection (used later) </li>  In Module1 (before the start of the Main subroutine), declare a boolean variable named isValid, as follows: 'If a validation error occurs, ' you will set this flag to False ' in the validation event handler. Private isValid As Boolean = True </li>  In the Main subroutine, create an XmlTextReader object to read an XML document from a text file. Then, create an XmlValidatingReader object to validate this XML data: Dim r As New XmlTextReader(&quot;C:\MyFolder\ProductWithDTD.xml&quot;) Dim v As New XmlValidatingReader(r) </li>  The XmlValidatingReader object has a ValidationType property, which indicates the type of validation 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 subroutine in step 8 of this section): AddHandler v.ValidationEventHandler, AddressOf MyValidationEventHandler </li>  Add the following code to read and validate the XML document. If any validation errors occur, MyValidationEventHandler will be called to handle the error. This subroutine will set isValid to False (see step 8 of this section). You can check the status of isValid after validation to see whether the document is valid or invalid. While v.Read ' Could add code here to process the content. End While v.Close

' Check whether the document is valid or invalid. If isValid Then Console.WriteLine(&quot;Document is valid&quot;) Else Console.WriteLine(&quot;Document is invalid&quot;) End If                   </li>  After the Main subroutine, write the MyValidationEventHandler subroutine, as follows: Public Sub MyValidationEventHandler(ByVal sender As Object, _                                   ByVal args As ValidationEventArgs) isValid = False Console.WriteLine(&quot;Validation event&quot; & vbCrLf & args.Message) End Sub </li> Build and run the application.

The application should report that the XML document is valid.</li> <li>In Visual Studio 2005 or in Visual Studio .NET, modify ProductWithDTD.xml to make it invalid (for example, delete the Rugby jersey/  element).</li> <li>Run the application again.

The application should display the following error message:

Validation event Element 'Product' has incomplete content. Expected 'ProductName'. An error occurred at file:///C:/MyFolder/ProductWithDTD.xml(4, 3). Document is invalid

</li></ol>

Create an XDR schema and link to the XML document
<ol> <li>In Visual Studio 2005 or in Visual Studio .NET, point to New on the File menu, and then click File.</li> <li>Select the Text File type, and then click Open.</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;>

<AttributeType name=&quot;ProductID&quot; dt:type=&quot;int&quot;/> <ElementType name=&quot;ProductName&quot; dt:type=&quot;string&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> </Schema> </li> <li>Save the file as Product.xdr in the same folder as your XML document.</li> <li> Reopen the original Product.xml, and then link it to the XDR schema, as follows: <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&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>

Perform validation by using an XDR schema
<ol> <li> Modify your application so that the XmlTextReader loads ProductWithXDR.xml, as follows: Dim r As New XmlTextReader(&quot;C:\MyFolder\ProductWithXDR.xml&quot;) </li> <li> Set the ValidationType to XDR so that the validating reader performs XDR validation, as follows: 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 make it deliberately invalid.</li> <li>Run the application again.

The application should report a validation error.</li></ol>

Create an XSD schema and link to the XML document
<ol> <li>In Visual Studio .NET, point to New on the File menu, and then click File.</li> <li>Select the Text File type, and then click Open.</li> <li> Add the following XSD schema definition 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 same folder as your XML document.</li> <li> Reopen the original Product.xml, and then link it to the XSD schema, as follows: <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&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>

Perform validation by using an XSD schema
<ol> <li> Modify your application so that the XmlTextReader loads ProductWithXSD.xml, as follows: Dim r As New XmlTextReader(&quot;C:\MyFolder\ProductWithXSD.xml&quot;) </li> <li> Set the ValidationType to Schema so that the validating reader performs XSD schema validation, as follows: v.ValidationType = ValidationType.Schema </li> <li>Build and run the application to validate the XML document by using the XSD schema.

The application should report that the XML document is valid.</li></ol>

Use namespaces in the XSD schema
<ol> <li> In Visual Studio 2005 or in Visual Studio .NET, open ProductWithXSD.xml. Declare a default namespace, urn:MyNamespace, in the document. Modify the XSD linkage to specify the XSD schema to validate content in this namespace, as follows: <?xml version=&quot;1.0&quot; encoding=&quot;utf-8&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 ProductWithXSD.xml.</li> <li> Open Product.xsd, click the XML tab, and then modify the  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 Product.xsd.</li> <li>Run the application to validate the XML document by using the XSD schema.</li></ol>

Cache namespaces
<ol> <li> In Visual Studio 2005 or in Visual Studio .NET, open Module1.vb. At the start of the Main subroutine, create an XmlSchemaCollection object, as follows: Dim cache As 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> After the code that creates the XmlValidatingReader object, add the following statement. This adds the schema cache to the XmlValidatingReader, so that the reader can use the in-memory schemas. v.Schemas.Add(cache) </li></ol>

Verification

 * 1) Build and run the application.
 * 2) Verify that the XML document is still being validated against the XSD schema.
 * 3) Make some changes to the ProductWithXSD.xml to deliberately make it invalid.
 * 4) Verify that the application detects these validation errors.

Keywords: kbvs2005swept kbvs2005applies kbhowtomaster KB315533

-

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

© Microsoft Corporation. All rights reserved.