Einfügen oder Importieren von XML-Schemata

Aktualisiert: November 2007

Ein XML-Schema kann die Elemente <xs:import />, <xs:include /> und <xs:redefine /> enthalten. Diese Schemaelemente verweisen auf andere XML-Schemata, mit denen die Struktur des Schemas ergänzt werden kann, in das Sie eingefügt bzw. importiert werden. Im SOM-API (Schemaobjektmodell) werden die Klassen XmlSchemaImport, XmlSchemaInclude und XmlSchemaRedefine diesen Elementen zugeordnet.

Einfügen oder Importieren eines XML-Schemas

Das folgende Codebeispiel ergänzt das im Thema Erstellen von XML-Schemata erstellte Kundenschema mit dem Adressschema. Wenn das Kundenschema mit dem Adressschema ergänzt wird, werden Adresstypen im Kundenschema verfügbar.

Das Adressschema kann mithilfe des <xs:include />-Elements oder des <xs:import />-Elements eingebunden werden, um Komponenten des Adressschemas im vorliegenden Zustand zu verwenden. Es kann auch mithilfe eines <xs:redefine />-Elements zum Ändern der Komponenten verwendet werden, um die Anforderungen des Kundenschemas zu erfüllen. Da das Adressschema einen targetNamespace aufweist, der sich von dem des Kundenschemas unterscheidet, wird Importsemantik in Form des <xs:import />-Elements verwendet.

Im Codebeispiel wird das Adressschema in den folgenden Schritten eingefügt.

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

  2. Ruft die kompilierten XmlSchema-Objekte für die Kunden- und Adressschemata aus dem XmlSchemaSet ab, indem die Schemas-Eigenschaft durchlaufen wird. Da die Schemata kompiliert sind, kann auf die Eigenschaften im Post-Schema-Compilation-Infoset (PSCI) zugegriffen werden.

  3. Erstellt ein XmlSchemaImport-Objekt, legt die Namespace-Eigenschaft des Imports auf den Namespace des Adressschemas fest, legt die Schema-Eigenschaft des Imports auf das XmlSchema-Objekt des Adressschemas fest, und fügt der Includes-Eigenschaft des Kundenschemas den Import hinzu.

  4. Das geänderte XmlSchema-Objekt des Kundenschemas wird mithilfe der Reprocess-Methode und der Compile-Methode der XmlSchemaSet-Klasse erneut verarbeitet, kompiliert und in die Konsole geschrieben.

  5. Schließlich werden alle in das Kundenschema importierten Schemata mithilfe der Includes-Eigenschaft des Kundenschemas rekursiv in die Konsole geschrieben. Die Includes-Eigenschaft bietet Zugriff auf alle einem Schema hinzugefügten Includes, Importe und Neudefinitionen.

Im Folgenden werden das gesamte Codebeispiel dargestellt und die Kunden- und Adressschemata auf der Konsole ausgegeben.

Imports System
Imports System.Xml
Imports System.Xml.Schema

Class XmlSchemaImportExample

    Shared Sub Main()
        ' Add the customer and address schemas to a new XmlSchemaSet and compile them.
        ' Any schema validation warnings and errors encountered reading or 
        ' compiling the schemas 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.Add("http://www.example.com/IPO", "address.xsd")
        schemaSet.Compile()

        ' Retrieve the compiled XmlSchema objects for the customer and
        ' address schema from the XmlSchemaSet by iterating over 
        ' the Schemas property.
        Dim customerSchema As XmlSchema = Nothing
        Dim addressSchema As XmlSchema = Nothing
        For Each schema As XmlSchema In schemaSet.Schemas()
            If schema.TargetNamespace = "http://www.tempuri.org" Then
                customerSchema = schema
            ElseIf schema.TargetNamespace = "http://www.example.com/IPO" Then
                addressSchema = schema
            End If
        Next

        ' Create an XmlSchemaImport object, set the Namespace property
        ' to the namespace of the address schema, the Schema property 
        ' to the address schema, and add it to the Includes property
        ' of the customer schema.
        Dim import As XmlSchemaImport = New XmlSchemaImport()
        import.Namespace = "http://www.example.com/IPO"
        import.Schema = addressSchema
        customerSchema.Includes.Add(import)

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

        ' Recursively write all of the schemas imported into the
        ' customer schema to the console using the Includes 
        ' property of the customer schema.
        RecurseExternals(customerSchema)
    End Sub

    Shared Sub RecurseExternals(ByVal schema As XmlSchema)
        For Each external As XmlSchemaExternal In Schema.Includes

            If Not external.SchemaLocation = Nothing Then
                Console.WriteLine("External SchemaLocation: {0}", external.SchemaLocation)
            End If

            If external.GetType() Is GetType(XmlSchemaImport) Then
                Dim import As XmlSchemaImport = CType(external, XmlSchemaImport)
                Console.WriteLine("Imported namespace: {0}", import.Namespace)
            End If

            If Not external.Schema Is Nothing Then
                external.Schema.Write(Console.Out)
                RecurseExternals(external.Schema)
            End If
        Next
    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 XmlSchemaImportExample
{
    static void Main(string[] args)
    {
        // Add the customer and address schemas to a new XmlSchemaSet and compile them.
        // Any schema validation warnings and errors encountered reading or 
        // compiling the schemas are handled by the ValidationEventHandler delegate.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add("http://www.tempuri.org", "customer.xsd");
        schemaSet.Add("http://www.example.com/IPO", "address.xsd");
        schemaSet.Compile();

        // Retrieve the compiled XmlSchema objects for the customer and
        // address schema from the XmlSchemaSet by iterating over 
        // the Schemas property.
        XmlSchema customerSchema = null;
        XmlSchema addressSchema = null;
        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            if (schema.TargetNamespace == "http://www.tempuri.org")
                customerSchema = schema;
            else if (schema.TargetNamespace == "http://www.example.com/IPO")
                addressSchema = schema;
        }

        // Create an XmlSchemaImport object, set the Namespace property
        // to the namespace of the address schema, the Schema property 
        // to the address schema, and add it to the Includes property
        // of the customer schema.
        XmlSchemaImport import = new XmlSchemaImport();
        import.Namespace = "http://www.example.com/IPO";
        import.Schema = addressSchema;
        customerSchema.Includes.Add(import);

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

        // Recursively write all of the schemas imported into the
        // customer schema to the console using the Includes 
        // property of the customer schema.
        RecurseExternals(customerSchema);       
    }

    static void RecurseExternals(XmlSchema schema)
    {
        foreach (XmlSchemaExternal external in schema.Includes)
        {
            if (external.SchemaLocation != null)
            {
                Console.WriteLine("External SchemaLocation: {0}", external.SchemaLocation);
            }

            if (external is XmlSchemaImport)
            {
                XmlSchemaImport import = external as XmlSchemaImport;
                Console.WriteLine("Imported namespace: {0}", import.Namespace);
            }

            if (external.Schema != null)
            {
                external.Schema.Write(Console.Out);
                RecurseExternals(external.Schema);
            }
        }
    }

    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 XmlSchemaImportExample
{
public:

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

        // Retrieve the compiled XmlSchema objects for the customer and
        // address schema from the XmlSchemaSet by iterating over 
        // the Schemas property.
        XmlSchema^ customerSchema = nullptr;
        XmlSchema^ addressSchema = nullptr;
        for each (XmlSchema^ schema in schemaSet->Schemas())
        {
            if (schema->TargetNamespace == "http://www.tempuri.org")
                customerSchema = schema;
            else if (schema->TargetNamespace == "http://www.example.com/IPO")
                addressSchema = schema;
        }

        // Create an XmlSchemaImport object, set the Namespace property
        // to the namespace of the address schema, the Schema property 
        // to the address schema, and add it to the Includes property
        // of the customer schema.
        XmlSchemaImport^ import = gcnew XmlSchemaImport();
        import->Namespace = "http://www.example.com/IPO";
        import->Schema = addressSchema;
        customerSchema->Includes->Add(import);

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

        // Recursively write all of the schemas imported into the
        // customer schema to the console using the Includes 
        // property of the customer schema.
        RecurseExternals(customerSchema);       
    }

    static void RecurseExternals(XmlSchema^ schema)
    {
        for each (XmlSchemaExternal^ external in schema->Includes)
        {
            if (external->SchemaLocation != nullptr)
            {
                Console::WriteLine("External SchemaLocation: {0}", external->SchemaLocation);
            }

            if (external::typeid == XmlSchemaImport::typeid)
            {
                XmlSchemaImport^ import = dynamic_cast<XmlSchemaImport^>(external);
                Console::WriteLine("Imported namespace: {0}", import->Namespace);
            }

            if (external->Schema != nullptr)
            {
                external->Schema->Write(Console::Out);
                RecurseExternals(external->Schema);
            }
        }
    }

    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()
{
    XmlSchemaImportExample::Main();
    return 0;
}

<?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:import namespace="http://www.example.com/IPO" />
  <xs:element name="Customer">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="FirstName" type="xs:string" />
        <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:schema>
<schema targetNamespace="http://www.example.com/IPO" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ipo="http://www.example.com/IPO">
  <annotation>
    <documentation xml:lang="en">
      Addresses for International Purchase order schema
      Copyright 2000 Example.com. All rights reserved.
    </documentation>
  </annotation>
  <complexType name="Address">
    <sequence>
      <element name="name"   type="string"/>
      <element name="street" type="string"/>
      <element name="city"   type="string"/>
    </sequence>
  </complexType>
  <complexType name="USAddress">
    <complexContent>
      <extension base="ipo:Address">
        <sequence>
          <element name="state" type="ipo:USState"/>
          <element name="zip"   type="positiveInteger"/>
        </sequence>
      </extension>
    </complexContent>
  </complexType>
  <!-- other Address derivations for more countries or regions -->
  <simpleType name="USState">
    <restriction base="string">
      <enumeration value="AK"/>
      <enumeration value="AL"/>
      <enumeration value="AR"/>
      <!-- and so on ... -->
    </restriction>
  </simpleType>
</schema>

Weitere Informationen zu den Elementen <xs:import />, <xs:include /> und <xs:redefine /> sowie zu den Klassen XmlSchemaImport, XmlSchemaInclude und XmlSchemaRedefine finden Sie in den W3C-XML-Schema-Spezifikationen und in der Referenzdokumentation zur System.Xml.Schema-Namespaceklasse.

Siehe auch

Konzepte

Übersicht über das XML-Schemaobjektmodell (SOM)

Lesen und Schreiben von XML-Schemata

Erstellen von XML-Schemata

Durchlaufen von XML-Schemata

Bearbeiten von XML-Schemata

"XmlSchemaSet" zur Kompilierung von Schemata