XML Validation in Visual Basic: DTD, XDR, and XSD 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, includingXmlTextReaderandXmlValidatingReader.System.Xml.Schema: This namespace contains classes specifically for XML schema validation, such asXmlSchemaCollectionandValidationType.
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.
- Open Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET.
- Navigate to File > New > File.
- Select XML File and click Open.
-
Add the following XML code to the newly created file:
<Product ProductID="123"> <ProductName>Rugby jersey</ProductName> </Product> -
Save this file as
Product.xmlin 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.
- In Visual Studio 2005 or Visual Studio .NET, go to File > New > File.
- Select Text File and click Open.
-
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
Productelement must contain aProductNameelement and have a required attributeProductID. TheProductNameelement should contain parsed character data (#PCDATA). -
Save this file as
Product.dtdin the same folder asProduct.xml(C:\MyFolder). -
Reopen
Product.xmlin Visual Studio. To link the XML document to the DTD, add aDOCTYPEdeclaration 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> -
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.
-
In Visual Studio 2005 or Visual Studio .NET, create a new Visual Basic Console Application project named
ValidateXmlUsingVB. -
Open
Module1.vb. At the beginning of the file, add the necessaryImportsstatements:Imports System.Xml ' For XmlTextReader and XmlValidatingReader Imports System.Xml.Schema ' For XmlSchemaCollection (used later) -
Before the
Mainsubroutine, declare a boolean variableisValidto 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 -
In the
Mainsubroutine, create anXmlTextReaderto read the XML file and anXmlValidatingReaderto perform validation:Dim r As New XmlTextReader("C:\MyFolder\ProductWithDTD.xml") Dim v As New XmlValidatingReader(r) -
Set the
ValidationTypeproperty of theXmlValidatingReadertoDTD:v.ValidationType = ValidationType.DTD -
Register a validation event handler to capture validation errors. We will implement
MyValidationEventHandlerin the next step:AddHandler v.ValidationEventHandler, AddressOf MyValidationEventHandler -
Add code to read and validate the XML document. The
MyValidationEventHandlersubroutine 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 -
After the
Mainsubroutine, implement theMyValidationEventHandlersubroutine:Public Sub MyValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs) isValid = False Console.WriteLine("Validation event" & vbCrLf & args.Message) End Sub -
Build and run the application. It should report “Document is valid” if
ProductWithDTD.xmlconforms toProduct.dtd. -
To test invalid scenarios, modify
ProductWithDTD.xmlby removing the<ProductName>element. -
Run the application again. This time, it should display a validation error message indicating that the document is invalid due to the missing
ProductNameelement.
Creating an XDR Schema and Linking it to the XML Document¶
Next, let’s explore XML validation using XDR schemas.
- In Visual Studio 2005 or Visual Studio .NET, go to File > New > File.
- Select Text File and click Open.
-
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.
-
Save this file as
Product.xdrin the same folder as your XML documents (C:\MyFolder). -
Reopen the original
Product.xmland 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> -
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.
-
Modify the
XmlTextReaderinModule1.vbto loadProductWithXDR.xml:Dim r As New XmlTextReader("C:\MyFolder\ProductWithXDR.xml") -
Set the
ValidationTypeof theXmlValidatingReadertoXDR:v.ValidationType = ValidationType.XDR -
Build and run the application. It should report “Document is valid” if
ProductWithXDR.xmlis valid againstProduct.xdr. -
Introduce an error in
ProductWithXDR.xmlto make it invalid (e.g., remove<ProductName>). -
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.
- In Visual Studio .NET, go to File > New > File.
- Select Text File and click Open.
-
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
Productelement with a sequence containingProductNameand a requiredProductIDattribute of type integer. -
Save this file as
Product.xsdin the same folder as your XML files (C:\MyFolder). -
Reopen the original
Product.xmland 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> -
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.
-
Set the
ValidationTypeofXmlValidatingReadertoSchema:v.ValidationType = ValidationType.Schema -
Build and run the application. It should validate
ProductWithXSD.xmlagainstProduct.xsdand 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.
-
Open
ProductWithXSD.xml. Declare a default namespaceurn:MyNamespaceand 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> -
Save
ProductWithXSD.xml. -
Open
Product.xsdand modify the<xsd:schema>start tag to target theurn:MyNamespacenamespace and require element qualification:<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:MyNamespace" elementFormDefault="qualified"> -
Save
Product.xsd. -
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.
-
Open
Module1.vb. At the beginning of theMainsubroutine, create anXmlSchemaCollectionobject:Dim cache As New XmlSchemaCollection() -
Add the
Product.xsdschema to the cache, associating it with theurn:MyNamespacenamespace:cache.Add("urn:MyNamespace", "C:\MyFolder\Product.xsd") -
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