Article ID: 318504
Article Last Modified on 9/16/2003
APPLIES TO
- Microsoft Visual C# .NET 2003 Standard Edition
- Microsoft Visual C# .NET 2002 Standard Edition
- Microsoft .NET Framework 1.0
- Microsoft .NET Framework 1.1
This article was previously published under Q318504
For a Microsoft Visual Basic .NET version of this article, see 317463.
IN THIS TASK
SUMMARY
This step-by-step article describes how to use XmlValidatingReader and XMLSchemaCollection objects to validate an Extensible Markup Language (XML) fragment against an XML schema.
XmlValidatingReader implements the XmlReader class and provides support for XML data validation. The Schemas property of XmlValidatingReader connects the reader to the schema files cached in an XmlSchemaCollection. The ValidationType property of XmlValidatingReader specifies the type of validation the reader should perform. If you set the property to ValidationType.None, you create a nonvalidating reader.
You can only add XML Schema Definition Language (XSD) schemas and XML-Data Reduced (XDR) schemas to XmlSchemaCollection. Use the Add method with a namespace URI to load schemas. For XML schemas, the typical namespace URI is the targetNamespace property of the schema.
back to the top
Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you will need:
- Microsoft Visual Studio .NET installed on a compatible Microsoft Windows operating system
This article assumes that you are familiar with the following topics:
- Visual C# .NET
- Basic XML standards
- XSD schemas
Create an XSD Schema
Paste the following code in a new text file named C:\Books.xsd:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:bookstore-schema" elementFormDefault="qualified" targetNamespace="urn:bookstore-schema"> <xsd:element name="bookstore" type="bookstoreType" /> <xsd:element name="comment" type="xsd:string" /> <xsd:element name="author" type="authorName"/> <xsd:complexType name="authorName"> <xsd:sequence> <xsd:element name="first-name" type="xsd:string" /> <xsd:element name="last-name" type="xsd:string" /> </xsd:sequence> </xsd:complexType> <xsd:complexType name="bookstoreType"> <xsd:sequence maxOccurs="unbounded"> <xsd:element name="book" type="bookType" /> <xsd:element ref="comment" minOccurs="0" /> </xsd:sequence> </xsd:complexType> <xsd:complexType name="bookType"> <xsd:sequence> <xsd:element name="title" type="xsd:string" /> <xsd:element ref="author" /> <xsd:element name="price" type="xsd:decimal" /> </xsd:sequence> <xsd:attribute name="genre" type="xsd:string" /> </xsd:complexType> </xsd:schema>
Create a Visual C# .NET Application
- Create a new Visual C# .NET Console application.
Replace the code in Class1.cs with the following code:
using System; using System.Xml; using System.Xml.Schema; namespace ConsoleApplication3 { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary> /// The main entry point for the application. /// </summary> System.Boolean m_success; [STAThread] static void Main(string[] args) { // // TODO: Add code to start application here. // XmlValidatingReader reader = null; XmlSchemaCollection myschema = new XmlSchemaCollection(); ValidationEventHandler eventHandler = new ValidationEventHandler(Class1.ShowCompileErrors ); try { //Create the XML fragment to be parsed. String xmlFrag = "<author xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + "<first-name>Herman</first-name>" + "<last-name>Melville</last-name>" + "</author>"; //Create the XmlParserContext. XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None); //Implement the reader. reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context); //Add the schema. myschema.Add("urn:bookstore-schema", "c:\\Books.xsd"); //Set the schema type and add the schema to the reader. reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(myschema); while (reader.Read()) { } Console.WriteLine("Completed validating xmlfragment"); } catch (XmlException XmlExp) { Console.WriteLine(XmlExp.Message); } catch(XmlSchemaException XmlSchExp) { Console.WriteLine(XmlSchExp.Message); } catch(Exception GenExp) { Console.WriteLine(GenExp.Message); } finally { Console.Read(); } } public static void ShowCompileErrors(object sender, ValidationEventArgs args) { Console.WriteLine("Validation Error: {0}", args.Message); } } }
When the following message is displayed in the output window, the XML fragment is a valid element:
Completed validating xmlfragment
NOTE: Only the type declarations and the top-level elements in the XML schema are validated against an XML schema. Subelements are considered as local and therefore cannot be validated. In order to validate a subelement, declare a top-level element and refer to that.
back to the top
REFERENCES
For additional information, click the article numbers below to view the articles in the Microsoft Knowledge Base:
307379 HOW TO: Validate an XML Document by Using DTD, XDR, or XSD in Visual C# .NET
313826 INFO: Roadmap for XML Schemas in the .NET Framework
313651 INFO: Roadmap for XML in the .NET Framework
For additional information, see the following MSDN Web sites:
System.Xml Namespace
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxml.asp
XML Web Services
http://msdn.microsoft.com/xml
Keywords: kbhowtomaster KB318504