HOW TO: Create Key Element for an XML Schema in Visual C# .NET (318506)



The information in this article applies to:

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

This article was previously published under Q318506
For a Microsoft Visual Basic .NET version of this article, see 317688.

IN THIS TASK

SUMMARY

Use this step-by-step guide to programmatically add a key element to an existing XML schema.

In relational data representation, a primary or unique key is used to identify a single instance of data or a row. To get similar unique representation of data in hierarchical data, a key element is required. Data representation in Extensible Markup Language (XML) is an example of hierarchical data representation. In XML schema, a key element makes the data representation unique. XMLSchemaKey identifies a key constraint that represents the World Wide Web Consortium KEY element.

The XMLSchema object contains the definition of a schema. All XML schema definition language (XSD) elements are children of the schema element. The XMLSchema object represents the World Wide Web Consortium SCHEMA element.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Visual Studio .NET installed on a compatible Microsoft Windows operating system.
This article assumes that you are familiar with the following topics:
  • Microsoft Visual C# .NET language.
  • XML standards.
  • XSD schemas.
back to the top

Create an XML Schema

In Notepad or another text editor, type or paste the following code into a text file and name it C:\Key.xsd.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
  <xs:element name="Parent">
    <xs:complexType>
      <xs:sequence>
        
      <xs:element name="Children">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Child" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                    <xs:attribute name="name"  type="xs:string" use="required"/>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>

      </xs:sequence>
    </xs:complexType>    
  </xs:element>
</xs:schema>
				
back to the top

Create a Visual C# .NET Application

  1. Create a new Visaul C# console application.
  2. Replace the code in the Class1.cs file with the following:
    using System;
    using System.Xml;
    using System.Xml.Schema;
    using System.IO;
    
    namespace ConsoleApplication4
    {
    	/// <summary>
    	/// Summary description for Class1.
    	/// </summary>
    	class Class1
    	{
    		/// <summary>
    		/// The main entry point for the application.
    		/// </summary>
    		[STAThread]
    		static void Main(string[] args)
    		{
    			ValidationEventHandler eventHandler = new ValidationEventHandler(Class1.ShowCompileErrors);
    			try
    			{
    				FileStream fstream = new FileStream("C:\\key.xsd", FileMode.Open);
    				XmlSchema myschema = new XmlSchema();
    
    				myschema = XmlSchema.Read(fstream, null);
    				myschema.Compile(eventHandler);
    
    				XmlSchemaObjectTable schemaobjecttable;
    				XmlSchemaElement ParentElement;
    				XmlQualifiedName ParentElementQName = new XmlQualifiedName("Parent", "");
    
    				schemaobjecttable = myschema.Elements;
    				if (schemaobjecttable.Contains(ParentElementQName)) 
    				{	
    					// Set the parent Node.
    					ParentElement = (XmlSchemaElement) schemaobjecttable[ParentElementQName];
    					// Create a new key element.
    					XmlSchemaKey element_key = new XmlSchemaKey();
    					element_key.Name = "IDKey";
    					element_key.Selector = new XmlSchemaXPath();
    					element_key.Selector.XPath = "Children/Child";
    
    					XmlSchemaXPath field = new XmlSchemaXPath();
    					field.XPath = "@name";
    					element_key.Fields.Add(field);
    					ParentElement.Constraints.Add(element_key);
    				}
    
    				myschema.Compile(eventHandler);
    
    				// Write to an external file.
    				StreamWriter strmWriter = new StreamWriter("c:\\NewSchema.xsd");
    				myschema.Write(strmWriter);
    				strmWriter.Close();
    				// Write to Output window.
    				StringWriter strWriter = new StringWriter();
    				myschema.Write(strWriter);
    				Console.WriteLine(strWriter.ToString());
    			}
    			
    			catch (XmlException XMLExp)
    			{
    				Console.WriteLine(XMLExp.Message);
    			}
    			catch (XmlSchemaException XmlSchemaExp)
    			{
    				Console.WriteLine(XmlSchemaExp.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);
    		}
    	}
    }
    
    						
    XmlSchemaObjectTable: In the Output window, notice the XSD has a new element:
    <xs:key name="IDKey">
          <xs:selector xpath="Children/Child" />
          <xs:field xpath="@name" />
        </xs:key>
    						
    A file named NewSchema.xsd is created in the root folder (C:\).
back to the top

REFERENCES

For additional information about the XmlSchemaKeyref class, see the Microsoft .NET Framework Software Developer's Kit (SDK): For additional information, click the article numbers below to view the articles in the Microsoft Knowledge Base:

313826 ROADMAP for XML Schemas in the .NET Framework

313651 ROADMAP for XML in the .NET

For additional information about the System.Xml namespace, see the Microsoft .NET Framework Software Developer's Kit (SDK): back to the top

Modification Type:MajorLast Reviewed:9/4/2003
Keywords:kbHOWTOmaster KB318506 kbAudDeveloper