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 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 TASKSUMMARY 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:
<Product ProductID="123">
<ProductName>Rugby jersey</ProductName>
</Product>
- Save the file as Product.xml in a new folder named
C:\MyFolder.
back to the top
Using the DTDCreate the DTD, and Link to XML Document- In Visual Studio .NET, create an empty text
file.
- 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)>
- Save the file as Product.dtd in the C:\MyFolder
directory.
- Open Product.xml in Visual Studio .NET.
- 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">
- Save the modified XML document as
ProductWithDTD.xml.
back to the top
Use the DTD to Validate the XML Document- In Visual Studio .NET, create a new Visual C# Console
Application project named ValidateXml.
- 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)
- 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. - 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);
- 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;
- 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);
- 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");
- 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);
}
- Build and run the application. The application should
report that the XML document is valid.
- In Visual Studio .NET, modify ProductWithDTD.xml to
invalidate it (for example, delete the "<ProductName>Rugby
jersey</ProductName>" element).
- 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 SchemaCreate the XDR Schema, and Link to XML Document- In Visual Studio .NET, create an empty text
file.
- 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>
- Save the file as Product.xdr in the C:\MyFolder
directory.
- 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>
- Save the modified XML document as
ProductWithXDR.xml.
back to the top
Use the XDR Schema to Validate the XML Document- Modify your application so that XmlTextReader loads ProductWithXDR.xml as follows:
XmlTextReader r = new XmlTextReader("C:\\MyFolder\\ProductWithXDR.xml");
- Set the ValidationType to XDR so that the validating reader performs XDR validation:
v.ValidationType = ValidationType.XDR;
- Build and run the application. The application should
report that the XML document is valid.
- Modify ProductWithXDR.xml to invalidate it.
- Build and run the application again. You should receive a
validation error.
back to the top
Using the XSD SchemaCreate the XSD Schema, and Link to XML Document- In Visual Studio .NET, create an empty text
file.
- 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>
- Save the file as Product.xsd in the C:\MyFolder
directory.
- 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>
- Save the modified XML document as
ProductWithXSD.xml.
back to the top
Use the XSD Schema to Validate the XML Document- Modify your application so that XmlTextReader loads ProductWithXSD.xml as follows:
XmlTextReader r = new XmlTextReader("C:\\MyFolder\\ProductWithXSD.xml");
- Set the ValidationType to Schema so that the validating reader performs XSD schema validation:
v.ValidationType = ValidationType.Schema;
- 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- In Visual Studio .NET, open ProductWithXSD.xml.
- 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>
- Save your changes to ProductWithXSD.xml.
- 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">
- Save your changes to Product.xsd.
- Build and run the application to use the XSD schema to
validate the XML document.
back to the top
Cache Namespaces- In Visual Studio .NET, open Class1.cs. Create an XmlSchemaCollection object at the beginning of the Main method as follows:
XmlSchemaCollection cache = new XmlSchemaCollection();
- 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");
- 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- Build and then run the application.
- Verify that the XML document is still validated against the
XSD schema.
- Modify the ProductWithXSD.xml to invalidate it.
- Verify that the application detects these validation
errors.
back to the top
Modification Type: | Major | Last Reviewed: | 12/5/2005 |
---|
Keywords: | kbHOWTOmaster KB307379 kbAudDeveloper |
---|
|