HOW TO: Create a Key Element for an XML Schema (317688)



The information in this article applies to:

  • Microsoft Visual Basic .NET (2002)
  • Microsoft Visual Basic .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 Q317688

SUMMARY

Use this step-by-step guide to programmatically add a key element to an existing Extensible Markup Language (XML) schema.

With relational data representation, you can create a primary key or a unique key to identify a single instance of data or a row. A key element is necessary to achieve a similar, unique representation of data in hierarchical data. XML data representation is an example of hierarchical data representation. In an XML schema, a key element makes the data representation unique. The XmlSchemaKey class identifies a key constraint and represents the World Wide Web Consortium (W3C) key element.

The XmlSchema object contains the definition of a schema. All XML Schema Definition Language (XSD) elements are children of the schema element. XmlSchema represents the World Wide Web Consortium schema element.

back to the top

Create an XML Schema

In Microsoft Notepad or another text editor, type or paste the following code, and then save the file as 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 Basic .NET Application

  1. Follow these steps to create a new Windows application in Visual Basic .NET:
    1. Start Microsoft Visual Studio .NET.
    2. On the File menu, point to New, and then click Project.
    3. In the New Project dialog box, click Visual Basic Projects under Project Types, click Windows Application under Templates, and then click OK.
  2. Drag a Button control from the toolbox to Form1.
  3. Import the following namespaces:
    Imports System.Xml
    Imports System.Xml.Schema
    Imports System.IO
    					
  4. Add the following code as a Sub procedure that triggers Validation events for the XmlSchema object:
    Public Sub ValidationEventHandler(ByVal sender As Object, ByVal args As System.Xml.Schema.ValidationEventArgs)
            Console.WriteLine(args.Message)
        End Sub
    					
  5. Add the following code in the Click event of Button1:
            Try
            Dim fstream As New FileStream("C:\key.xsd", FileMode.Open)
            Dim myschema As New XmlSchema()
    
            myschema = XmlSchema.Read(fstream, Nothing)
            myschema.Compile(AddressOf ValidationEventHandler)
    
            Dim schemaobjecttable As XmlSchemaObjectTable
            Dim ParentElement As XmlSchemaElement
            Dim ParentElementQName As New XmlQualifiedName("Parent", "")
    
            schemaobjecttable = myschema.Elements
            If schemaobjecttable.Contains(ParentElementQName) Then
                ParentElement = CType(schemaobjecttable.Item(ParentElementQName), XmlSchemaElement)
    
                Dim element_key As New XmlSchemaKey()
                element_key.Name = "IDKey"
                element_key.Selector = New XmlSchemaXPath()
                element_key.Selector.XPath = "Children/Child"
    
                Dim field As New XmlSchemaXPath()
                field.XPath = "@name"
                element_key.Fields.Add(field)
                ParentElement.Constraints.Add(element_key)
            End If
    
            myschema.Compile(AddressOf ValidationEventHandler)
    
             'Write to an external file.
            Dim strmWriter As New StreamWriter("c:\NewSchema.xsd")
            myschema.Write(strmWriter)
            strmWriter.Close()
            'Write to the Output window.
            Dim strWriter As New StringWriter()
            myschema.Write(strWriter)
            Console.WriteLine(strWriter.ToString)
            Catch GenExp As Exception
                Console.WriteLine(GenExp.Message)
            Catch XMLExp As XmlException
                Console.WriteLine(XMLExp.Message)
            Catch XmlSchemaExp As XmlSchemaException
                Console.WriteLine(XmlSchemaExp.Message)
            End Try
    					
  6. In the Output window, notice that the XSD has a new element:
    <xs:key name="IDKey">
          <xs:selector xpath="Children/Child" />
          <xs:field xpath="@name" />
        </xs:key>
    						
    Additionally, the NewSchema.xsd file is created in the root folder (C:\).
back to the top

REFERENCES

For additional information about the XmlSchemaKeyref class, see the following .NET Framework Class Library documentation: back to the top

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