XML スキーマの編集

XML スキーマの編集は、スキーマ オブジェクト モデル (SOM) の最も重要な機能の 1 つです。 XML スキーマの既存の値を変更する場合、SOM のスキーマ コンパイル前のすべてのプロパティを使用できます。 その後、XML スキーマを再コンパイルすると、変更が反映されます。

SOM に読み込まれたスキーマを編集する場合、最初にスキーマの走査を行います。 スキーマを編集する際には、事前に SOM API を使用したスキーマの走査をよく理解しておく必要があります。 また、スキーマのコンパイル後の情報セット (PSCI) のうち、スキーマのコンパイル前のプロパティとコンパイル後のプロパティについてもよく理解しておく必要があります。

XML スキーマの編集

このセクションには、2 種類のコード サンプルが用意されています。これらはいずれも「XML スキーマの作成」トピックで作成したカスタム スキーマを編集します。 最初のコード サンプルは、PhoneNumber 要素に新しい Customer 要素を追加します。2 番目のコード サンプルは、Title 要素に新しい FirstName 属性を追加します。 また、最初のサンプルは、スキーマのコンパイル前の XmlSchema.Elements コレクションをカスタム スキーマを走査する手段として使用しますが、2 番目のコード サンプルはスキーマのコンパイル後の XmlSchema.Items コレクションを使用します。

PhoneNumber 要素の例

この最初のコード サンプルでは、カスタム スキーマの PhoneNumber 要素に新しい Customer 要素を追加します。 このコード サンプルでは、次の手順でカスタム スキーマの編集を行います。

  1. カスタム スキーマを新しい XmlSchemaSet オブジェクトに追加し、コンパイルします。 スキーマの読み取りまたはコンパイル時に発生するスキーマ検証に関する警告とエラーは、ValidationEventHandler デリゲートで処理されます。

  2. XmlSchema プロパティを反復処理して、XmlSchemaSet からコンパイルされた Schemas オブジェクトを取得します。 スキーマはコンパイルされているため、スキーマのコンパイル後の情報セット (PSCI) プロパティにアクセスできます。

  3. PhoneNumber クラスを使用する XmlSchemaElement 要素を作成し、xs:string クラスおよび XmlSchemaSimpleType クラスを使用する XmlSchemaSimpleTypeRestriction 単純型の制限を作成し、制限の Facets プロパティに pattern ファセットを追加し、単純型の Content プロパティに制限を追加して、SchemaType 要素の PhoneNumber に単純型を追加します。

  4. スキーマ コンパイル後の XmlSchema.Elements コレクションの Values コレクションで、それぞれの XmlSchemaElement を反復処理します。

  5. 要素の QualifiedName"Customer" である場合、Customer クラスを使用する複合型の XmlSchemaComplexType 要素と XmlSchemaSequence クラスを使用する複合型の sequence のパーティクルを取得します。

  6. シーケンスのスキーマ コンパイル前の Items コレクションを使用する既存の FirstName 要素および LastName 要素を格納するシーケンスに、新しい PhoneNumber 要素を追加します。

  7. 最後に、XmlSchema クラスの Reprocess および Compile メソッドを使用して、変更された XmlSchemaSet オブジェクトの再処理とコンパイルを行って、コンソールに出力します。

完全なコード サンプルを次に示します。

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;

ref class XmlSchemaEditExample
{
public:

    static void Main()
    {
        // Add the customer schema to a new XmlSchemaSet and compile it.
        // Any schema validation warnings and errors encountered reading or 
        // compiling the schema are handled by the ValidationEventHandler delegate.
        XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet();
        schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback);
        schemaSet->Add("http://www.tempuri.org", "customer.xsd");
        schemaSet->Compile();

        // Retrieve the compiled XmlSchema object from the XmlSchemaSet
        // by iterating over the Schemas property.
        XmlSchema^ customerSchema = nullptr;
        for each (XmlSchema^ schema in schemaSet->Schemas())
        {
            customerSchema = schema;
        }

        // Create the PhoneNumber element.
        XmlSchemaElement^ phoneElement = gcnew XmlSchemaElement();
        phoneElement->Name = "PhoneNumber";

        // Create the xs:string simple type restriction.
        XmlSchemaSimpleType^ phoneType = gcnew XmlSchemaSimpleType();
        XmlSchemaSimpleTypeRestriction^ restriction =
            gcnew XmlSchemaSimpleTypeRestriction();
        restriction->BaseTypeName = gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // Add a pattern facet to the restriction.
        XmlSchemaPatternFacet^ phonePattern = gcnew XmlSchemaPatternFacet();
        phonePattern->Value = "\\d{3}-\\d{3}-\\d(4)";
        restriction->Facets->Add(phonePattern);

        // Add the restriction to the Content property of the simple type
        // and the simple type to the SchemaType of the PhoneNumber element.
        phoneType->Content = restriction;
        phoneElement->SchemaType = phoneType;

        // Iterate over each XmlSchemaElement in the Values collection
        // of the Elements property.
        for each (XmlSchemaElement^ element in customerSchema->Elements->Values)
        {
            // If the qualified name of the element is "Customer", 
            // get the complex type of the Customer element  
            // and the sequence particle of the complex type.
            if (element->QualifiedName->Name->Equals("Customer"))
            {
                XmlSchemaComplexType^ customerType =
                    dynamic_cast<XmlSchemaComplexType^>(element->ElementSchemaType);
                XmlSchemaSequence^ sequence =
                    dynamic_cast<XmlSchemaSequence^>(customerType->Particle);

                // Add the new PhoneNumber element to the sequence.
                sequence->Items->Add(phoneElement);
            }
        }

        // Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet->Reprocess(customerSchema);
        schemaSet->Compile();
        customerSchema->Write(Console::Out);
    }

    static void ValidationCallback(Object^ sender, ValidationEventArgs^ args)
    {
        if (args->Severity == XmlSeverityType::Warning)
            Console::Write("WARNING: ");
        else if (args->Severity == XmlSeverityType::Error)
            Console::Write("ERROR: ");

        Console::WriteLine(args->Message);
    }
};

int main()
{
    XmlSchemaEditExample::Main();
    return 0;
}
using System;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaEditExample
{
    static void Main(string[] args)
    {
        // Add the customer schema to a new XmlSchemaSet and compile it.
        // Any schema validation warnings and errors encountered reading or
        // compiling the schema are handled by the ValidationEventHandler delegate.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add("http://www.tempuri.org", "customer.xsd");
        schemaSet.Compile();

        // Retrieve the compiled XmlSchema object from the XmlSchemaSet
        // by iterating over the Schemas property.
        XmlSchema customerSchema = null;
        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            customerSchema = schema;
        }

        // Create the PhoneNumber element.
        XmlSchemaElement phoneElement = new XmlSchemaElement();
        phoneElement.Name = "PhoneNumber";

        // Create the xs:string simple type restriction.
        XmlSchemaSimpleType phoneType = new XmlSchemaSimpleType();
        XmlSchemaSimpleTypeRestriction restriction =
            new XmlSchemaSimpleTypeRestriction();
        restriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // Add a pattern facet to the restriction.
        XmlSchemaPatternFacet phonePattern = new XmlSchemaPatternFacet();
        phonePattern.Value = "\\d{3}-\\d{3}-\\d(4)";
        restriction.Facets.Add(phonePattern);

        // Add the restriction to the Content property of the simple type
        // and the simple type to the SchemaType of the PhoneNumber element.
        phoneType.Content = restriction;
        phoneElement.SchemaType = phoneType;

        // Iterate over each XmlSchemaElement in the Values collection
        // of the Elements property.
        foreach (XmlSchemaElement element in customerSchema.Elements.Values)
        {
            // If the qualified name of the element is "Customer",
            // get the complex type of the Customer element
            // and the sequence particle of the complex type.
            if (element.QualifiedName.Name.Equals("Customer"))
            {
                XmlSchemaComplexType customerType =
                    element.ElementSchemaType as XmlSchemaComplexType;
                XmlSchemaSequence sequence =
                    customerType.Particle as XmlSchemaSequence;

                // Add the new PhoneNumber element to the sequence.
                sequence.Items.Add(phoneElement);
            }
        }

        // Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet.Reprocess(customerSchema);
        schemaSet.Compile();
        customerSchema.Write(Console.Out);
    }

    static void ValidationCallback(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("WARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("ERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlSchemaEditExample

    Shared Sub Main()

        ' Add the customer schema to a new XmlSchemaSet and compile it.
        ' Any schema validation warnings and errors encountered reading or 
        ' compiling the schema are handled by the ValidationEventHandler delegate.
        Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
        AddHandler schemaSet.ValidationEventHandler, AddressOf ValidationCallback
        schemaSet.Add("http://www.tempuri.org", "customer.xsd")
        schemaSet.Compile()

        ' Retrieve the compiled XmlSchema object from the XmlSchemaSet
        ' by iterating over the Schemas property.
        Dim customerSchema As XmlSchema = Nothing
        For Each schema As XmlSchema In schemaSet.Schemas()
            customerSchema = schema
        Next

        ' Create the PhoneNumber element.
        Dim phoneElement As XmlSchemaElement = New XmlSchemaElement()
        phoneElement.Name = "PhoneNumber"

        ' Create the xs:string simple type restriction.
        Dim phoneType As XmlSchemaSimpleType = New XmlSchemaSimpleType()
        Dim restriction As XmlSchemaSimpleTypeRestriction = _
            New XmlSchemaSimpleTypeRestriction()
        restriction.BaseTypeName = New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")

        ' Add a pattern facet to the restriction.
        Dim phonePattern As XmlSchemaPatternFacet = New XmlSchemaPatternFacet()
        phonePattern.Value = "\\d{3}-\\d{3}-\\d(4)"
        restriction.Facets.Add(phonePattern)

        ' Add the restriction to the Content property of the simple type
        ' and the simple type to the SchemaType of the PhoneNumber element.
        phoneType.Content = restriction
        phoneElement.SchemaType = phoneType

        ' Iterate over each XmlSchemaElement in the Values collection
        ' of the Elements property.
        For Each element As XmlSchemaElement In customerSchema.Elements.Values

            ' If the qualified name of the element is "Customer", 
            ' get the complex type of the Customer element  
            ' and the sequence particle of the complex type.
            If element.QualifiedName.Name.Equals("Customer") Then

                Dim customerType As XmlSchemaComplexType = _
                    CType(element.ElementSchemaType, XmlSchemaComplexType)
                Dim sequence As XmlSchemaSequence = _
                    CType(customerType.Particle, XmlSchemaSequence)

                ' Add the new PhoneNumber element to the sequence.
                sequence.Items.Add(phoneElement)
            End If
        Next

        ' Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet.Reprocess(customerSchema)
        schemaSet.Compile()
        customerSchema.Write(Console.Out)
    End Sub

    Shared Sub ValidationCallback(ByVal sender As Object, ByVal args As ValidationEventArgs)
        If args.Severity = XmlSeverityType.Warning Then
            Console.Write("WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write("ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)
    End Sub

End Class

変更後のカスタム スキーマ (「XML スキーマの作成」トピックで作成) を次に示します。

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://www.tempuri.org" targetNamespace="http://www.tempuri.org" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Customer">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="FirstName" type="xs:string" />
        <xs:element name="LastName" type="tns:LastNameType" />
        <xs:element name="PhoneNumber">           <xs:simpleType>             <xs:restriction base="xs:string">               <xs:pattern value="\d{3}-\d{3}-\d(4)" />             </xs:restriction>           </xs:simpleType>         </xs:element>
      </xs:sequence>
      <xs:attribute name="CustomerId" type="xs:positiveInteger" use="required" />
    </xs:complexType>
  </xs:element>
  <xs:simpleType name="LastNameType">
    <xs:restriction base="xs:string">
      <xs:maxLength value="20" />
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

Title 属性の例

この 2 番目のコード サンプルでは、カスタム スキーマの Title 要素に新しい FirstName 属性を追加します。 最初のコード サンプルでは、FirstName 要素の型が xs:string になっています。 FirstName 要素が文字列のコンテンツと同時に属性を持つには、単純なコンテンツの拡張コンテンツ モデルを使用してこの要素の型を複合型に変更する必要があります。

このコード サンプルでは、次の手順でカスタム スキーマの編集を行います。

  1. カスタム スキーマを新しい XmlSchemaSet オブジェクトに追加し、コンパイルします。 スキーマの読み取りまたはコンパイル時に発生するスキーマ検証に関する警告とエラーは、ValidationEventHandler デリゲートで処理されます。

  2. XmlSchema プロパティを反復処理して、XmlSchemaSet からコンパイルされた Schemas オブジェクトを取得します。 スキーマはコンパイルされているため、スキーマのコンパイル後の情報セット (PSCI) プロパティにアクセスできます。

  3. FirstName クラスを使用して XmlSchemaComplexType 要素に対する複合型を新しく作成します。

  4. xs:string および XmlSchemaSimpleContent クラスを使用して、XmlSchemaSimpleContentExtension の基本型を使った単純なコンテンツの拡張型を新しく作成します。

  5. TitleXmlSchemaAttribute を使用して、SchemaTypeName クラスを使用する xs:string 属性を新しく作成し、その属性を単純なコンテンツの拡張型に追加します。

  6. 単純なコンテンツのコンテンツ モデルを単純なコンテンツの拡張型に設定し、複合型のコンテンツ モデルを単純なコンテンツに設定します。

  7. スキーマ コンパイル前の XmlSchema.Items コレクションに、新しい複合型を追加します。

  8. スキーマのコンパイル前の XmlSchemaObject コレクションで、それぞれの XmlSchema.Items を反復処理します。

Note

FirstName 要素はスキーマのグローバル要素ではないため、XmlSchema.Items または XmlSchema.Elements コレクションでは使用できません。 コード サンプルでは、FirstName 要素を検索するために、最初に Customer 要素の検索を行います。

最初のコード サンプルでは、スキーマ コンパイル後の XmlSchema.Elements コレクションを使用してスキーマを走査しました。 このサンプルでは、スキーマ コンパイル前の XmlSchema.Items コレクションを使用してスキーマを走査します。 どちらのコレクションでもスキーマのグローバル要素にアクセスできますが、Items コレクションで反復処理を行う場合、スキーマ内のすべてのグローバル要素に対して反復処理を行う必要があり、スキーマに PSCI プロパティが存在しないため、処理時間が長くなります。 PSCI コレクション (XmlSchema.ElementsXmlSchema.AttributesXmlSchema.SchemaTypes など) では、グローバルな要素、属性、型、および PSCI プロパティに直接アクセスできます。

  1. XmlSchemaObject が要素 (その QualifiedName"Customer") である場合、Customer クラスを使用する複合型の XmlSchemaComplexType 要素と XmlSchemaSequence クラスを使用する複合型の sequence のパーティクルを取得します。

  2. スキーマのコンパイル前の XmlSchemaParticle コレクションで、それぞれの XmlSchemaSequence.Items を反復処理します。

  3. XmlSchemaParticle が要素 (その QualifiedName"FirstName") である場合、SchemaTypeName 要素の FirstName を新しい FirstName 複合型に設定します。

  4. 最後に、XmlSchema クラスの Reprocess および Compile メソッドを使用して、変更された XmlSchemaSet オブジェクトの再処理とコンパイルを行って、コンソールに出力します。

完全なコード サンプルを次に示します。

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;

ref class XmlSchemaEditExample
{
public:

    static void Main()
    {
        // Add the customer schema to a new XmlSchemaSet and compile it.
        // Any schema validation warnings and errors encountered reading or 
        // compiling the schema are handled by the ValidationEventHandler delegate.
        XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet();
        schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback);
        schemaSet->Add("http://www.tempuri.org", "customer.xsd");
        schemaSet->Compile();

        // Retrieve the compiled XmlSchema object from the XmlSchemaSet
        // by iterating over the Schemas property.
        XmlSchema^ customerSchema = nullptr;
        for each (XmlSchema^ schema in schemaSet->Schemas())
        {
            customerSchema = schema;
        }

        // Create a complex type for the FirstName element.
        XmlSchemaComplexType^ complexType = gcnew XmlSchemaComplexType();
        complexType->Name = "FirstNameComplexType";
        
        // Create a simple content extension with a base type of xs:string.
        XmlSchemaSimpleContent^ simpleContent = gcnew XmlSchemaSimpleContent();
        XmlSchemaSimpleContentExtension^ simpleContentExtension =
            gcnew XmlSchemaSimpleContentExtension();
        simpleContentExtension->BaseTypeName =
            gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // Create the new Title attribute with a SchemaTypeName of xs:string
        // and add it to the simple content extension.
        XmlSchemaAttribute^ attribute = gcnew XmlSchemaAttribute();
        attribute->Name = "Title";
        attribute->SchemaTypeName =
            gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        simpleContentExtension->Attributes->Add(attribute);

        // Set the content model of the simple content to the simple content extension
        // and the content model of the complex type to the simple content.
        simpleContent->Content = simpleContentExtension;
        complexType->ContentModel = simpleContent;

        // Add the new complex type to the pre-schema-compilation Items collection.
        customerSchema->Items->Add(complexType);

        // Iterate over each XmlSchemaObject in the pre-schema-compilation
        // Items collection.
        for each (XmlSchemaObject^ schemaObject in customerSchema->Items)
        {
            // If the XmlSchemaObject is an element, whose QualifiedName
            // is "Customer", get the complex type of the Customer element
            // and the sequence particle of the complex type.
            if (schemaObject::typeid == XmlSchemaElement::typeid)
            {
                XmlSchemaElement^ element = dynamic_cast<XmlSchemaElement^>(schemaObject);

                if (element->QualifiedName->Name->Equals("Customer"))
                {
                    XmlSchemaComplexType^ customerType =
                        dynamic_cast<XmlSchemaComplexType^>(element->ElementSchemaType);

                    XmlSchemaSequence^ sequence =
                        dynamic_cast<XmlSchemaSequence^>(customerType->Particle);

                    // Iterate over each XmlSchemaParticle in the pre-schema-compilation
                    // Items property.
                    for each (XmlSchemaParticle^ particle in sequence->Items)
                    {
                        // If the XmlSchemaParticle is an element, who's QualifiedName
                        // is "FirstName", set the SchemaTypeName of the FirstName element
                        // to the new FirstName complex type.
                        if (particle::typeid == XmlSchemaElement::typeid)
                        {
                            XmlSchemaElement^ childElement =
                                dynamic_cast<XmlSchemaElement^>(particle);

                            if (childElement->Name->Equals("FirstName"))
                            {
                                childElement->SchemaTypeName =
                                    gcnew XmlQualifiedName("FirstNameComplexType",
                                    "http://www.tempuri.org");
                            }
                        }
                    }
                }
            }
        }

        // Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet->Reprocess(customerSchema);
        schemaSet->Compile();
        customerSchema->Write(Console::Out);
    }

    static void ValidationCallback(Object^ sender, ValidationEventArgs^ args)
    {
        if (args->Severity == XmlSeverityType::Warning)
            Console::Write("WARNING: ");
        else if (args->Severity == XmlSeverityType::Error)
            Console::Write("ERROR: ");

        Console::WriteLine(args->Message);
    }
};

int main()
{
    XmlSchemaEditExample::Main();
    return 0;
}
using System;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaEditExample
{
    static void Main(string[] args)
    {
        // Add the customer schema to a new XmlSchemaSet and compile it.
        // Any schema validation warnings and errors encountered reading or
        // compiling the schema are handled by the ValidationEventHandler delegate.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add("http://www.tempuri.org", "customer.xsd");
        schemaSet.Compile();

        // Retrieve the compiled XmlSchema object from the XmlSchemaSet
        // by iterating over the Schemas property.
        XmlSchema customerSchema = null;
        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            customerSchema = schema;
        }

        // Create a complex type for the FirstName element.
        XmlSchemaComplexType complexType = new XmlSchemaComplexType();
        complexType.Name = "FirstNameComplexType";

        // Create a simple content extension with a base type of xs:string.
        XmlSchemaSimpleContent simpleContent = new XmlSchemaSimpleContent();
        XmlSchemaSimpleContentExtension simpleContentExtension =
            new XmlSchemaSimpleContentExtension();
        simpleContentExtension.BaseTypeName =
            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // Create the new Title attribute with a SchemaTypeName of xs:string
        // and add it to the simple content extension.
        XmlSchemaAttribute attribute = new XmlSchemaAttribute();
        attribute.Name = "Title";
        attribute.SchemaTypeName =
            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        simpleContentExtension.Attributes.Add(attribute);

        // Set the content model of the simple content to the simple content extension
        // and the content model of the complex type to the simple content.
        simpleContent.Content = simpleContentExtension;
        complexType.ContentModel = simpleContent;

        // Add the new complex type to the pre-schema-compilation Items collection.
        customerSchema.Items.Add(complexType);

        // Iterate over each XmlSchemaObject in the pre-schema-compilation
        // Items collection.
        foreach (XmlSchemaObject schemaObject in customerSchema.Items)
        {
            // If the XmlSchemaObject is an element, whose QualifiedName
            // is "Customer", get the complex type of the Customer element
            // and the sequence particle of the complex type.
            if (schemaObject is XmlSchemaElement)
            {
                XmlSchemaElement element = schemaObject as XmlSchemaElement;

                if (element.QualifiedName.Name.Equals("Customer"))
                {
                    XmlSchemaComplexType customerType =
                        element.ElementSchemaType as XmlSchemaComplexType;

                    XmlSchemaSequence sequence =
                        customerType.Particle as XmlSchemaSequence;

                    // Iterate over each XmlSchemaParticle in the pre-schema-compilation
                    // Items property.
                    foreach (XmlSchemaParticle particle in sequence.Items)
                    {
                        // If the XmlSchemaParticle is an element, who's QualifiedName
                        // is "FirstName", set the SchemaTypeName of the FirstName element
                        // to the new FirstName complex type.
                        if (particle is XmlSchemaElement)
                        {
                            XmlSchemaElement childElement =
                                particle as XmlSchemaElement;

                            if (childElement.Name.Equals("FirstName"))
                            {
                                childElement.SchemaTypeName =
                                    new XmlQualifiedName("FirstNameComplexType",
                                    "http://www.tempuri.org");
                            }
                        }
                    }
                }
            }
        }

        // Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet.Reprocess(customerSchema);
        schemaSet.Compile();
        customerSchema.Write(Console.Out);
    }

    static void ValidationCallback(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("WARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("ERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlSchemaEditExample

    Shared Sub Main()

        ' Add the customer schema to a new XmlSchemaSet and compile it.
        ' Any schema validation warnings and errors encountered reading or 
        ' compiling the schema are handled by the ValidationEventHandler delegate.
        Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
        AddHandler schemaSet.ValidationEventHandler, AddressOf ValidationCallback
        schemaSet.Add("http://www.tempuri.org", "customer.xsd")
        schemaSet.Compile()

        ' Retrieve the compiled XmlSchema object from the XmlSchemaSet
        ' by iterating over the Schemas property.
        Dim customerSchema As XmlSchema = Nothing
        For Each schema As XmlSchema In schemaSet.Schemas()
            customerSchema = schema
        Next

        ' Create a complex type for the FirstName element.
        Dim complexType As XmlSchemaComplexType = New XmlSchemaComplexType()
        complexType.Name = "FirstNameComplexType"

        ' Create a simple content extension with a base type of xs:string.
        Dim simpleContent As XmlSchemaSimpleContent = New XmlSchemaSimpleContent()
        Dim simpleContentExtension As XmlSchemaSimpleContentExtension = _
            New XmlSchemaSimpleContentExtension()
        simpleContentExtension.BaseTypeName = _
            New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")

        ' Create the new Title attribute with a SchemaTypeName of xs:string
        ' and add it to the simple content extension.
        Dim attribute As XmlSchemaAttribute = New XmlSchemaAttribute()
        attribute.Name = "Title"
        attribute.SchemaTypeName = _
            New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
        simpleContentExtension.Attributes.Add(attribute)

        ' Set the content model of the simple content to the simple content extension
        ' and the content model of the complex type to the simple content.
        simpleContent.Content = simpleContentExtension
        complexType.ContentModel = simpleContent

        ' Add the new complex type to the pre-schema-compilation Items collection.
        customerSchema.Items.Add(complexType)

        ' Iterate over each XmlSchemaObject in the pre-schema-compilation
        ' Items collection.
        For Each schemaObject As XmlSchemaObject In customerSchema.Items

            ' If the XmlSchemaObject is an element, whose QualifiedName
            ' is "Customer", get the complex type of the Customer element
            ' and the sequence particle of the complex type.
            If schemaObject.GetType() Is GetType(XmlSchemaElement) Then

                Dim element As XmlSchemaElement = CType(schemaObject, XmlSchemaElement)

                If (element.QualifiedName.Name.Equals("Customer")) Then
                    Dim customerType As XmlSchemaComplexType = _
                        CType(element.ElementSchemaType, XmlSchemaComplexType)

                    Dim sequence As XmlSchemaSequence = _
                       CType(customerType.Particle, XmlSchemaSequence)

                    ' Iterate over each XmlSchemaParticle in the pre-schema-compilation
                    ' Items property.
                    For Each particle As XmlSchemaParticle In sequence.Items

                        ' If the XmlSchemaParticle is an element, who's QualifiedName
                        ' is "FirstName", set the SchemaTypeName of the FirstName element
                        ' to the new FirstName complex type.
                        If particle.GetType() Is GetType(XmlSchemaElement) Then
                            Dim childElement As XmlSchemaElement = _
                                CType(particle, XmlSchemaElement)

                            If childElement.Name.Equals("FirstName") Then
                                childElement.SchemaTypeName = _
                                   New XmlQualifiedName("FirstNameComplexType", _
                                  "http://www.tempuri.org")
                            End If
                        End If
                    Next
                End If
            End If
        Next

        ' Reprocess and compile the modified XmlSchema object and write it to the console.
        schemaSet.Reprocess(customerSchema)
        schemaSet.Compile()
        customerSchema.Write(Console.Out)
    End Sub

    Shared Sub ValidationCallback(ByVal sender As Object, ByVal args As ValidationEventArgs)
        If args.Severity = XmlSeverityType.Warning Then
            Console.Write("WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write("ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)
    End Sub

End Class

変更後のカスタム スキーマ (「XML スキーマの作成」トピックで作成) を次に示します。

<?xml version="1.0" encoding=" utf-8"?>
<xs:schema xmlns:tns="http://www.tempuri.org" targetNamespace="http://www.tempuri.org" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Customer">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="FirstName" type="tns:FirstNameComplexType" />
        <xs:element name="LastName" type="tns:LastNameType" />
      </xs:sequence>
      <xs:attribute name="CustomerId" type="xs:positiveInteger" use="required" />
    </xs:complexType>
  </xs:element>
  <xs:simpleType name="LastNameType">
    <xs:restriction base="xs:string">
      <xs:maxLength value="20" />
    </xs:restriction>
  </xs:simpleType>
  <xs:complexType name="FirstNameComplexType">     <xs:simpleContent>       <xs:extension base="xs:string">         <xs:attribute name="Title" type="xs:string" />       </xs:extension>     </xs:simpleContent>   </xs:complexType>
</xs:schema>

関連項目