You are currently offline, waiting for your internet to reconnect

HOW TO: Modify an XML Schema by Using System.Xml.Schema Classes in Visual C# .NET

This article was previously published under Q318502
For a Microsoft Visual Basic .NET version of this article, see 317903.
This article references the following .NET Framework Class Library namespaces:
  • System.Xml
  • System.Xml.Schema

IN THIS TASK

SUMMARY
This step-by-step article shows how to modify an existing XML schema.

The System.Xml.Schema namespace contains the XML classes that provide standards-based support for XML schema definition language (XSD) schemas.

The XmlSchema class contains the definition of a schema. All XSD elements are children of the schema element; this represents the World Wide Web Consortium (W3C) schema element. You can use these classes to generate new XML schemas or modify existing ones.

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 the XML Schema File

  1. In Microsoft Notepad or another text editor, type or paste the following code into a new file, and then name the file C:\Book.xsd:
    <xs:schema xmlns="urn:bookstore-schema"         targetNamespace="urn:bookstore-schema"         xmlns:xs="http://www.w3.org/2001/XMLSchema">   <xs:element name="book" type="booktype"/>      <xs:complexType name="booktype">         <xs:sequence>            <xs:element name="author" type="xs:string"/>               <xs:element name="price" type="xs:decimal" />               </xs:sequence>      </xs:complexType></xs:schema>					
  2. Modify the author of the element name.
  3. Set minOccurs and maxOccurs properties.
  4. Modify the data type of the element price.
  5. Add a new element publisher.
back to the top

Create a Sample Visual C# .NET Application to Modify the Schema

To add a new publisher child element to the book element of the schema, follow these steps:
  1. Create a new Visual C# Console application project.
  2. Replace the code in the Class1.cs module with the following:
    using System;using System.Xml;using System.Xml.Schema;using System.IO;namespace ConsoleApplication1{   class Class1   {      [STAThread]      static void Main(string[] args)      {         FileStream fs;         XmlSchema schema;         ValidationEventHandler eventHandler = new ValidationEventHandler(Class1.ShowCompileErrors);         try         {            // Open the XSD file.            fs = new FileStream("c:\\book.xsd", FileMode.Open);             // Read the schema into an XMLSchema object.            schema = XmlSchema.Read(fs, eventHandler);                      // Compile the schema.            schema.Compile(eventHandler);                                              // Define an XMLSchemaObjectTable to read the schema elements.            XmlSchemaObjectTable schematable;            schematable = schema.Elements;            // Define a QualifiedName to identify the elements.            XmlQualifiedName qname = new XmlQualifiedName("book", "urn:bookstore-schema");            XmlSchemaElement bookelement = new XmlSchemaElement();            XmlSchemaComplexType complexelement = new XmlSchemaComplexType();                        //  See if the XmlSchemaObjectTable has the element.            if (schematable.Contains(qname))            {               bookelement = (XmlSchemaElement) schematable[qname];             // See if the element type is booktype.            // If it is, create a new element and add it to the             // schema.            if (bookelement.SchemaTypeName.ToString() == "urn:bookstore-schema:booktype")               {                  complexelement = (XmlSchemaComplexType) schema.SchemaTypes[bookelement.SchemaTypeName];                                    XmlSchemaSequence seqelement = new XmlSchemaSequence();                  seqelement = (XmlSchemaSequence) complexelement.Particle;                  // Modify author element to show maxOccurs and minOccurs.                  XmlSchemaElement eleauthor = new XmlSchemaElement();                  eleauthor =  (XmlSchemaElement) seqelement.Items[0];                  // Modify the author element name.                  eleauthor.Name = "authorname";                  // Add min and max.                  eleauthor.MaxOccurs = 1;                  eleauthor.MinOccurs = 1;                  XmlSchemaElement eleprice = new XmlSchemaElement();                  eleprice = (XmlSchemaElement) seqelement.Items[1];                  // Modify the type of price element.                  eleprice.SchemaTypeName = new XmlQualifiedName("decimal", "http://www.w3.org/2001/XMLSchema");               // Create a New element and add it to the schema.               // XmlSchemaSequence seqelement = new XmlSchemaSequence();               // seqelement = (XmlSchemaSequence) complexelement.Particle;               XmlSchemaElement Newelement = new XmlSchemaElement();               Newelement.Name = "Publisher";               Newelement.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");               seqelement.Items.Add(Newelement);               }                  }            // Display the schema in the Output window.            schema.Write(Console.Out);            Console.Read();            // Save the output to the hard disk.            StreamWriter strmWrtr = new StreamWriter("c:\\newbook.xsd", false);            schema.Write(strmWrtr);         }          catch (XmlSchemaException schemaEx)         {            Console.WriteLine(schemaEx.Message);         }         catch (XmlException xmlEx)         {            Console.WriteLine(xmlEx.Message);         }         catch (Exception ex)         {            Console.WriteLine(ex.Message);         }         finally         {               Console.Read();         }      }      public static void ShowCompileErrors(object sender, ValidationEventArgs args)      {         Console.WriteLine("Validation Error: {0}", args.Message);      }   }} 						
    XmlSchemaObjectTable is a collection class that provides read-only helpers for XmlSchemaObject objects. This class provides the collections for contained elements in the schema as collections that are accessed from the XmlSchema class (for example, Attributes, AttributeGroups, and Elements).

    Because you are trying to add a child element publisher to a book element, add the new element to the XmlSchemaSequence. The XmlSchemaSequence class represents the World Wide Web Consortium SEQUENCE (compositor) element.
  3. Press F5 to build and run the application.

    The new schema that includes the publisher element appears in the Console output area. Also, the XSD file named Newbook.xsd is created in the C:\ folder.
back to the top
REFERENCES
For additional information, click the article numbers below to view the articles in the Microsoft Knowledge Base:
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: back to the top
EditXmlSchema ModifyXmlSchema
Properties

Article ID: 318502 - Last Review: 09/04/2003 20:54:37 - Revision: 2.2

  • Microsoft .NET Framework 1.0
  • Microsoft .NET Framework 1.1
  • kbbcl kbhowtomaster KB318502
Feedback