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



The information in this article applies to:

  • Microsoft Visual C# .NET (2003)
  • Microsoft Visual C# .NET (2002)
  • Microsoft XML Classes (included with the .NET Framework 1.1)
  • Microsoft XML Classes (included with the .NET Framework 1.0)

This article was previously published under Q307379

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

  1. Start Visual Studio .NET.
  2. Create a new XML file on your local computer.
  3. Add the following data to the XML document to represent a product in a catalog:
    <Product ProductID="123">
       <ProductName>Rugby jersey</ProductName>
    </Product>
    					
  4. Save the file as Product.xml in a new folder named C:\MyFolder.
back to the top

Using the DTD

Create the DTD, and Link to XML Document

  1. In Visual Studio .NET, create an empty text file.
  2. 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)>
    					
  3. Save the file as Product.dtd in the C:\MyFolder directory.
  4. Open Product.xml in Visual Studio .NET.
  5. Add the following DOCTYPE statement to the top of Product.xml to link the XML document to the DTD file:
    <?xml version="1.0"?>
    <!DOCTYPE Product SYSTEM "Product.dtd">
    					
  6. Save the modified XML document as ProductWithDTD.xml.
back to the top

Use the DTD to Validate the XML Document

  1. In Visual Studio .NET, create a new Visual C# Console Application project named ValidateXml.
  2. 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)
    					
  3. 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. 
  4. 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("C:\\MyFolder\\ProductWithDTD.xml");
    XmlValidatingReader v = new XmlValidatingReader(r);
    					
  5. 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;
    					
  6. 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);
    					
  7. 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("Document is valid");
    else
       Console.WriteLine("Document is invalid");
    					
  8. Write the MyValidationEventHandler method after the Main method as follows:
    public static void MyValidationEventHandler(object sender, 
                                                ValidationEventArgs args) 
    {
       isValid = false;
       Console.WriteLine("Validation event\n" + args.Message);
    }
    					
  9. Build and run the application. The application should report that the XML document is valid.
  10. In Visual Studio .NET, modify ProductWithDTD.xml to invalidate it (for example, delete the "<ProductName>Rugby jersey</ProductName>" element).
  11. 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
back to the top

Using the XDR Schema

Create the XDR Schema, and Link to XML Document

  1. In Visual Studio .NET, create an empty text file.
  2. Add the following XDR schema definitions to the file to describe the grammar of the XML document:
    <?xml version="1.0"?>
    <Schema name="ProductSchema" 
            xmlns="urn:schemas-microsoft-com:xml-data"
            xmlns:dt="urn:schemas-microsoft-com:datatypes">
    
       <ElementType name="Product" content="eltOnly">
          <attribute type="ProductID" required="yes"/>
          <element type="ProductName"/>
       </ElementType>
    
       <AttributeType name="ProductID" dt:type="int"/>
       <ElementType name="ProductName" dt:type="string"/>
    </Schema>
    					
  3. Save the file as Product.xdr in the C:\MyFolder directory.
  4. Open the original Product.xml file, and link it to the XDR schema as follows:
    <?xml version="1.0"?>
    <Product ProductID="123" xmlns="x-schema:Product.xdr"> 
       <ProductName>Rugby jersey</ProductName>
    </Product>
    					
  5. Save the modified XML document as ProductWithXDR.xml.
back to the top

Use the XDR Schema to Validate the XML Document

  1. Modify your application so that XmlTextReader loads ProductWithXDR.xml as follows:
    XmlTextReader r = new XmlTextReader("C:\\MyFolder\\ProductWithXDR.xml");
    					
  2. Set the ValidationType to XDR so that the validating reader performs XDR validation:
    v.ValidationType = ValidationType.XDR;
    					
  3. Build and run the application. The application should report that the XML document is valid.
  4. Modify ProductWithXDR.xml to invalidate it.
  5. Build and run the application again. You should receive a validation error.
back to the top

Using the XSD Schema

Create the XSD Schema, and Link to XML Document

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

Use the XSD Schema to Validate the XML Document

  1. Modify your application so that XmlTextReader loads ProductWithXSD.xml as follows:
    XmlTextReader r = new XmlTextReader("C:\\MyFolder\\ProductWithXSD.xml");
    					
  2. Set the ValidationType to Schema so that the validating reader performs XSD schema validation:
    v.ValidationType = ValidationType.Schema;
    					
  3. Build and run the application to use the XSD schema to validate the XML document.
back to the top

Use Namespaces in the XSD Schema

  1. In Visual Studio .NET, open ProductWithXSD.xml.
  2. 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="1.0"?>
    <Product ProductID="123" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="urn:MyNamespace"
             xsi:schemaLocation="urn:MyNamespace Product.xsd">
       <ProductName>Rugby jersey</ProductName>
    </Product>
    					
  3. Save your changes to ProductWithXSD.xml.
  4. 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="http://www.w3.org/2001/XMLSchema"
                targetNamespace="urn:MyNamespace"
                elementFormDefault="qualified">
    					
  5. Save your changes to Product.xsd.
  6. Build and run the application to use the XSD schema to validate the XML document.
back to the top

Cache Namespaces

  1. In Visual Studio .NET, open Class1.cs. Create an XmlSchemaCollection object at the beginning of the Main method as follows:
    XmlSchemaCollection cache = new XmlSchemaCollection();
    					
  2. 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("urn:MyNamespace", "C:\\MyFolder\\Product.xsd");
    					
  3. 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);
    					
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

Modification Type:MajorLast Reviewed:12/5/2005
Keywords:kbHOWTOmaster KB307379 kbAudDeveloper