XML Validation in Visual Basic: DTD, XDR, and XSD Techniques

Table of Contents

XML Validation Techniques

Extensible Markup Language (XML) has become a cornerstone for data interchange across diverse applications and organizational boundaries. Its flexibility and robust structure allow for complex data representation. To ensure the integrity and consistency of XML documents, validation against a defined grammar is crucial. This process verifies that the XML document adheres to a specific structure and content model. This article will explore how to validate XML documents in Visual Basic using different schema languages: Document Type Definition (DTD), XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD).

Understanding XML Schema Languages

To effectively validate XML documents, it’s essential to understand the schema languages used to define the rules. These languages act as blueprints, specifying the allowed elements, attributes, their relationships, and data types within an XML document. Choosing the right schema language depends on the specific requirements of your application and the level of complexity you need to enforce. Let’s briefly introduce DTD, XDR, and XSD.

Document Type Definition (DTD)

DTD is one of the earliest schema languages for XML. It defines the structure of an XML document by listing the elements, attributes, and their relationships. DTDs are relatively simple to write and understand, making them a good starting point for basic XML validation. However, DTDs have limitations, particularly in terms of data type support and namespace handling. They are less expressive compared to newer schema languages. Despite these limitations, DTDs are still supported in the .NET Framework for backward compatibility and simpler validation scenarios.

XML-Data Reduced (XDR) Schema

XDR schema was introduced by Microsoft as an early XML schema language. It offers more features than DTD, including richer data type support. XDR schemas are written in XML syntax, making them more consistent with the documents they describe. While XDR was a step forward from DTD, it has been superseded by XSD, which is now the W3C recommended standard for XML schemas. XDR is still supported in the .NET Framework, but XSD is generally preferred for new development.

XML Schema Definition (XSD)

XSD is the W3C standard schema language for XML. It is a powerful and versatile language that provides extensive control over the structure, content, and data types of XML documents. XSD supports namespaces, complex data types, and a wide range of validation rules. It is the recommended schema language for .NET Framework development and is widely adopted across the industry. XSD offers significant advantages in terms of expressiveness, flexibility, and industry support, making it the preferred choice for most XML validation needs.

Prerequisites

Before diving into the practical examples, ensure you have the necessary tools and knowledge:

  • Microsoft Visual Basic 2005 or Microsoft Visual Basic .NET: This tutorial is designed for these development environments. You will need one of these versions installed on your system to follow along with the code examples.
  • Basic understanding of Visual Basic .NET: Familiarity with Visual Basic .NET syntax is essential to understand and implement the code snippets provided.
  • Fundamental XML concepts: A working knowledge of XML, including elements, attributes, and the concept of XML validation, is expected.

This article will utilize the following .NET Framework namespaces:

  • System.Xml: This namespace provides fundamental classes for working with XML documents, including XmlTextReader and XmlValidatingReader.
  • System.Xml.Schema: This namespace contains classes specifically for XML schema validation, such as XmlSchemaCollection and ValidationType.

Creating an XML Document

Let’s start by creating a sample XML document that we will use for validation throughout this article. This document will represent a product in a catalog.

  1. Open Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET.
  2. Navigate to File > New > File.
  3. Select XML File and click Open.
  4. Add the following XML code to the newly created file:

    <Product ProductID="123">
        <ProductName>Rugby jersey</ProductName>
    </Product>
    
  5. Save this file as Product.xml in a readily accessible folder, for example, C:\MyFolder. We will refer to this location in the code examples.

Defining a DTD and Linking it to the XML Document

Now, let’s create a DTD to define the structure for our Product.xml document.

  1. In Visual Studio 2005 or Visual Studio .NET, go to File > New > File.
  2. Select Text File and click Open.
  3. Add the following DTD declarations to define the XML structure:

    <!ELEMENT Product (ProductName)>
    <!ATTLIST Product ProductID CDATA #REQUIRED>
    <!ELEMENT ProductName (#PCDATA)>
    

    This DTD specifies that the Product element must contain a ProductName element and have a required attribute ProductID. The ProductName element should contain parsed character data (#PCDATA).

  4. Save this file as Product.dtd in the same folder as Product.xml (C:\MyFolder).

  5. Reopen Product.xml in Visual Studio. To link the XML document to the DTD, add a DOCTYPE declaration below the XML version declaration:

    <?xml version="1.0" encoding="utf-8" ?>
    <!DOCTYPE Product SYSTEM "Product.dtd">
    <Product ProductID="123">
        <ProductName>Rugby jersey</ProductName>
    </Product>
    
  6. Save the modified XML document as ProductWithDTD.xml.

Performing Validation Using a DTD

Now, let’s write Visual Basic code to validate ProductWithDTD.xml against the Product.dtd we created.

  1. In Visual Studio 2005 or Visual Studio .NET, create a new Visual Basic Console Application project named ValidateXmlUsingVB.

    Visual Basic Console Application

  2. Open Module1.vb. At the beginning of the file, add the necessary Imports statements:

    Imports System.Xml ' For XmlTextReader and XmlValidatingReader
    Imports System.Xml.Schema ' For XmlSchemaCollection (used later)
    
  3. Before the Main subroutine, declare a boolean variable isValid to track validation status:

    'If a validation error occurs,
    ' you will set this flag to False
    ' in the validation event handler.
    Private isValid As Boolean = True
    
  4. In the Main subroutine, create an XmlTextReader to read the XML file and an XmlValidatingReader to perform validation:

    Dim r As New XmlTextReader("C:\MyFolder\ProductWithDTD.xml")
    Dim v As New XmlValidatingReader(r)
    
  5. Set the ValidationType property of the XmlValidatingReader to DTD:

    v.ValidationType = ValidationType.DTD
    
  6. Register a validation event handler to capture validation errors. We will implement MyValidationEventHandler in the next step:

    AddHandler v.ValidationEventHandler, AddressOf MyValidationEventHandler
    
  7. Add code to read and validate the XML document. The MyValidationEventHandler subroutine will be called if validation errors occur:

    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("Document is valid")
    Else
        Console.WriteLine("Document is invalid")
    End If
    
  8. After the Main subroutine, implement the MyValidationEventHandler subroutine:

    Public Sub MyValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)
        isValid = False
        Console.WriteLine("Validation event" & vbCrLf & args.Message)
    End Sub
    
  9. Build and run the application. It should report “Document is valid” if ProductWithDTD.xml conforms to Product.dtd.

  10. To test invalid scenarios, modify ProductWithDTD.xml by removing the <ProductName> element.

  11. Run the application again. This time, it should display a validation error message indicating that the document is invalid due to the missing ProductName element.

Creating an XDR Schema and Linking it to the XML Document

Next, let’s explore XML validation using XDR schemas.

  1. In Visual Studio 2005 or Visual Studio .NET, go to File > New > File.
  2. Select Text File and click Open.
  3. Add the following XDR schema definitions to describe the XML structure:

    <?xml version="1.0"?>
    <Schema name="ProductSchema"
     xmlns="urn:schemas-microsoft-com:xml-data"
     xmlns:dt="urn:schemas-microsoft-com:datatypes">
    
        <AttributeType name="ProductID" dt:type="int"/>
        <ElementType name="ProductName" dt:type="string"/>
    
        <ElementType name="Product" content="eltOnly">
            <attribute type="ProductID" required="yes"/>
            <element type="ProductName"/>
        </ElementType>
    </Schema>
    

    This XDR schema defines attributes and elements with specific data types and structure.

  4. Save this file as Product.xdr in the same folder as your XML documents (C:\MyFolder).

  5. Reopen the original Product.xml and link it to the XDR schema. Modify the root element to include the schema reference:

    <?xml version="1.0" encoding="utf-8" ?>
    <Product ProductID="123" xmlns="x-schema:Product.xdr">
        <ProductName>Rugby jersey</ProductName>
    </Product>
    
  6. Save the modified XML document as ProductWithXDR.xml.

Performing Validation Using an XDR Schema

Now, let’s adapt our Visual Basic application to validate against the XDR schema.

  1. Modify the XmlTextReader in Module1.vb to load ProductWithXDR.xml:

    Dim r As New XmlTextReader("C:\MyFolder\ProductWithXDR.xml")
    
  2. Set the ValidationType of the XmlValidatingReader to XDR:

    v.ValidationType = ValidationType.XDR
    
  3. Build and run the application. It should report “Document is valid” if ProductWithXDR.xml is valid against Product.xdr.

  4. Introduce an error in ProductWithXDR.xml to make it invalid (e.g., remove <ProductName>).

  5. Run the application again. It should now report a validation error, indicating that the document is invalid according to the XDR schema.

Creating an XSD Schema and Linking it to the XML Document

Finally, let’s explore XML validation using the more modern and recommended XSD schema.

  1. In Visual Studio .NET, go to File > New > File.
  2. Select Text File and click Open.
  3. Add the following XSD schema definition:

    <?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>
    

    This XSD schema defines the Product element with a sequence containing ProductName and a required ProductID attribute of type integer.

  4. Save this file as Product.xsd in the same folder as your XML files (C:\MyFolder).

  5. Reopen the original Product.xml and link it to the XSD schema. Modify the root element to include the schema location:

    <?xml version="1.0" encoding="utf-8" ?>
    <Product ProductID="123"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="Product.xsd">
        <ProductName>Rugby jersey</ProductName>
    </Product>
    
  6. Save the modified XML document as ProductWithXSD.xml.

Performing Validation Using an XSD Schema

Let’s adjust our Visual Basic application to perform XSD schema validation.

  1. Set the ValidationType of XmlValidatingReader to Schema:

    v.ValidationType = ValidationType.Schema
    
  2. Build and run the application. It should validate ProductWithXSD.xml against Product.xsd and report “Document is valid” if successful.

Utilizing Namespaces in XSD Schema

Namespaces are essential for managing XML vocabularies, especially in complex systems. Let’s see how to incorporate namespaces into our XSD validation.

  1. Open ProductWithXSD.xml. Declare a default namespace urn:MyNamespace and modify the XSD schema location to reflect this namespace:

    <?xml version="1.0" encoding="utf-8"?>
    <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>
    
  2. Save ProductWithXSD.xml.

  3. Open Product.xsd and modify the <xsd:schema> start tag to target the urn:MyNamespace namespace and require element qualification:

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
     targetNamespace="urn:MyNamespace"
     elementFormDefault="qualified">
    
  4. Save Product.xsd.

  5. Run the application. It should now validate the namespaced XML document against the namespaced XSD schema.

Caching Namespaces for Optimization

For applications that perform frequent XML validation, caching schemas can significantly improve performance. The XmlSchemaCollection class allows you to store schemas in memory.

  1. Open Module1.vb. At the beginning of the Main subroutine, create an XmlSchemaCollection object:

    Dim cache As New XmlSchemaCollection()
    
  2. Add the Product.xsd schema to the cache, associating it with the urn:MyNamespace namespace:

    cache.Add("urn:MyNamespace", "C:\MyFolder\Product.xsd")
    
  3. After creating the XmlValidatingReader, add the schema cache to it:

    v.Schemas.Add(cache)
    

By caching the schema, subsequent validations against documents using the same schema will be faster as the schema doesn’t need to be loaded from disk each time.

Conclusion

This article demonstrated how to validate XML documents in Visual Basic using DTD, XDR, and XSD schemas. We covered the steps to create and link schemas to XML documents and how to use the XmlValidatingReader class for validation. Additionally, we explored namespace usage in XSD schemas and techniques for optimizing validation performance through schema caching. Understanding these techniques is crucial for building robust and reliable XML-based applications in Visual Basic .NET.

Feel free to share your experiences or questions about XML validation in the comments below!

Post a Comment