Bearbeiten von XML-Schemata

Aktualisiert: November 2007

Die Bearbeitung von XML-Schemata ist eines der wichtigsten Features des Schemaobjektmodells (SOM). Alle Eigenschaften des SOM vor der Kompilierung des Schemas können zum Ändern der vorhandenen Werte eines XML-Schemas verwendet werden. Das XML-Schema kann dann erneut kompiliert werden, um die Änderungen widerzuspiegeln.

Der erste Bearbeitungsschritt eines in das DOM geladenen Schemas ist das Durchlaufen des Schemas. Sie sollten mit dem Durchlaufen eines Schemas mithilfe der SOM-API vertraut sein, bevor Sie versuchen, ein Schema zu bearbeiten. Sie sollten auch mit den Eigenschaften vor und nach der Kompilierung des Schemas im Post-Schema-Compilation-Infoset (PSCI) vertraut sein.

Bearbeiten eines XML-Schemas

In diesem Abschnitt finden Sie zwei Codebeispiele, in denen das im Thema Erstellen von XML-Schemata erstellte Kundenschema bearbeitet wird. Im ersten Codebeispiel wird dem Customer-Element ein neues PhoneNumber-Element hinzugefügt, und im zweiten Codebeispiel wird dem FirstName-Element ein neues Title-Attribut hinzugefügt. Im ersten Beispiel wird die XmlSchema.Elements-Auflistung nach der Kompilierung des Schemas zum Durchlaufen des Kundenschemas verwendet, während im zweiten Codebeispiel die XmlSchema.Items-Auflistung vor der Kompilierung des Schemas verwendet wird.

Beispiel: "PhoneNumber"-Element

Im ersten Codebeispiel wird dem Customer-Element des Kundenschemas ein neues PhoneNumber-Element hinzugefügt. Im Codebeispiel wird das Kundenschema in den folgenden Schritten bearbeitet.

  1. Fügt das Kundenschema einem neuen XmlSchemaSet-Objekt hinzu und kompiliert es anschließend. Alle beim Lesen oder Kompilieren des Schemas aufgetretenen Schemavalidierungswarnungen und -fehler werden vom ValidationEventHandler-Delegaten behandelt.

  2. Ruft das kompilierte XmlSchema-Objekt aus XmlSchemaSet ab, indem die Schemas-Eigenschaft durchlaufen wird. Da das Schema kompiliert ist, kann auf die Eigenschaften im PSCI zugegriffen werden.

  3. Erstellt mithilfe der XmlSchemaElement-Klasse das PhoneNumber-Element und mithilfe der XmlSchemaSimpleType-Klasse und der XmlSchemaSimpleTypeRestriction-Klasse die Einschränkung des einfachen xs:string-Typs. Fügt außerdem der Facets-Eigenschaft der Einschränkung ein pattern-Facet hinzu, und fügt der Content-Eigenschaft des einfachen Typs die Einschränkung sowie dem SchemaType des PhoneNumber-Elements den einfachen Typ hinzu.

  4. Durchläuft jedes XmlSchemaElement in der Values-Auflistung der XmlSchema.Elements-Auflistung nach der Kompilierung des Schemas.

  5. Ruft mithilfe der XmlSchemaComplexType-Klasse den komplexen Typ des Customer-Elements ab und mithilfe der XmlSchemaSequence-Klasse den sequence-Partikel des komplexen Typs, wenn der QualifiedName des Elements "Customer" ist.

  6. Fügt der Sequenz mit dem vorhandenen FirstName-Element und dem vorhandenen LastName-Element mithilfe der Items-Auflistung vor der Kompilierung des Schemas das neue PhoneNumber-Element hinzu.

  7. Schließlich wird das geänderte XmlSchema-Objekt mithilfe der Reprocess-Methode und der Compile-Methode der XmlSchemaSet-Klasse erneut verarbeitet, kompiliert und in die Konsole geschrieben.

Nachfolgend ist das vollständige Codebeispiel angegeben.

Imports System
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
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);
    }
}
#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;
}

Im Folgenden finden Sie das geänderte Schema, das im Thema Erstellen von XML-Schemata erstellt wurde.

<?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>

Beispiel: "Title"-Attribut

Im zweiten Codebeispiel wird dem FirstName-Element des Kundenschemas ein neues Title-Attribut hinzugefügt. Im ersten Codebeispiel ist der Typ des FirstName-Elements xs:string. Da das FirstName-Element ein Attribut mit Zeichenfolgeninhalt enthalten soll, muss sein Typ mit einem Inhaltsmodell zur Erweiterung einfachen Inhalts in einen komplexen Typ geändert werden.

Im Codebeispiel wird das Kundenschema in den folgenden Schritten bearbeitet.

  1. Fügt das Kundenschema einem neuen XmlSchemaSet-Objekt hinzu und kompiliert es anschließend. Alle beim Lesen oder Kompilieren des Schemas aufgetretenen Schemavalidierungswarnungen und -fehler werden vom ValidationEventHandler-Delegaten behandelt.

  2. Ruft das kompilierte XmlSchema-Objekt aus XmlSchemaSet ab, indem die Schemas-Eigenschaft durchlaufen wird. Da das Schema kompiliert ist, kann auf die Eigenschaften im PSCI zugegriffen werden.

  3. Erstellt mithilfe der XmlSchemaComplexType-Klasse einen neuen komplexen Typ für das FirstName-Element.

  4. Erstellt mithilfe der XmlSchemaSimpleContent-Klasse und der XmlSchemaSimpleContentExtension-Klasse eine neue Erweiterung für einfachen Inhalt mit dem Basistyp xs:string.

  5. Erstellt mithilfe der XmlSchemaAttribute-Klasse das neue Title-Attribut mit dem SchemaTypeName von xs:string, und fügt der Erweiterung für einfachen Inhalt das Attribut hinzu.

  6. Legt das Inhaltsmodell für einfachen Inhalt auf die Erweiterung für einfachen Inhalt und das Inhaltsmodell für den komplexen Typ auf den einfachen Inhalt fest.

  7. Fügt der XmlSchema.Items-Auflistung vor der Kompilierung des Schemas den neuen komplexen Typ hinzu.

  8. Durchläuft alle XmlSchemaObject in der XmlSchema.Items-Auflistung vor der Kompilierung des Schemas.

Hinweis:

Da das FirstName-Element in diesem Schema kein globales Element ist, ist es in der XmlSchema.Items-Auflistung oder der XmlSchema.Elements-Auflistung nicht verfügbar. Im Codebeispiel wird das FirstName-Element gefunden, indem zuerst nach dem Customer-Element gesucht wird.

Im ersten Codebeispiel wird das Schema mithilfe der XmlSchema.Elements-Auflistung nach der Kompilierung des Schemas durchlaufen. In diesem Beispiel wird das Schema mithilfe der XmlSchema.Items-Auflistung vor der Kompilierung des Schemas durchlaufen. Während beide Auflistungen den Zugriff auf die globalen Elemente im Schema bereitstellen, ist das Durchlaufen der Items-Auflistung zeitaufwendiger, da alle globalen Elemente im Schema durchlaufen werden müssen und das Schema keine PSCI-Eigenschaften aufweist. Die PSCI-Auflistungen (XmlSchema.Elements, XmlSchema.Attributes, XmlSchema.SchemaTypes usw.) bieten direkten Zugriff auf die globalen Elemente, Attribute und Typen mit den PSCI-Eigenschaften.

  1. Ruft mithilfe der XmlSchemaComplexType-Klasse den komplexen Typ des Customer-Elements ab sowie mithilfe der XmlSchemaSequence-Klasse den sequence-Partikel des komplexen Typs, wenn das XmlSchemaObject ein Element ist, dessen QualifiedName gleich "Customer" ist.

  2. Durchläuft alle XmlSchemaParticle in der XmlSchemaSequence.Items-Auflistung vor der Kompilierung des Schemas.

  3. Legt den SchemaTypeName des FirstName-Elements auf den neuen komplexen FirstName-Typ fest, wenn XmlSchemaParticle ein Element ist, dessen QualifiedName gleich "FirstName" ist.

  4. Schließlich wird das geänderte XmlSchema-Objekt mithilfe der Reprocess-Methode und der Compile-Methode der XmlSchemaSet-Klasse erneut verarbeitet, kompiliert und in die Konsole geschrieben.

Nachfolgend ist das vollständige Codebeispiel angegeben.

Imports System
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
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);
    }
}
#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;
}

Im Folgenden finden Sie das geänderte Schema, das im Thema Erstellen von XML-Schemata erstellt wurde.

<?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>

Siehe auch

Konzepte

Übersicht über das XML-Schemaobjektmodell (SOM)

Lesen und Schreiben von XML-Schemata

Erstellen von XML-Schemata

Durchlaufen von XML-Schemata

Einfügen oder Importieren von XML-Schemata

"XmlSchemaSet" zur Kompilierung von Schemata

Post-Schema-Compilation Infoset