Inclusione o importazione di schemi XML

Uno schema XML può contenere elementi <xs:import />, <xs:include /> e <xs:redefine />. Questi elementi dello schema fanno riferimento ad altri schemi XML che possono essere usati per integrare la struttura dello schema che li include o importa. Nell'API del modello SOM (Schema Object Model), a questi elementi sono associate le classi XmlSchemaImport, XmlSchemaInclude e XmlSchemaRedefine.

Inclusione o importazione di uno schema XML

L'esempio di codice seguente integra lo schema del cliente creato nell'argomento Compilazione di XML Schema con lo schema dell'indirizzo. L'integrazione dello schema del cliente con lo schema dell'indirizzo rende disponibili i tipi di indirizzo nello schema del cliente.

È possibile incorporare lo schema dell'indirizzo mediante l'elemento <xs:include /> o <xs:import /> per usare i componenti dello schema dell'indirizzo senza apportarvi modifiche oppure mediante un elemento <xs:redefine /> per modificare i componenti in modo che soddisfino le esigenze dello schema del cliente. Poiché nello schema dell'indirizzo targetNamespace è diverso da quello dello schema del cliente, vengono usati l'elemento <xs:import /> e quindi la semantica di importazione.

L'esempio di codice consente di includere lo schema dell'indirizzo eseguendo i passaggi seguenti.

  1. Aggiunge lo schema del cliente e lo schema dell'indirizzo a un nuovo oggetto XmlSchemaSet, quindi li compila. Eventuali avvisi ed errori di convalida dello schema rilevati durante la lettura e la compilazione degli schemi vengono gestiti dal delegato ValidationEventHandler.

  2. Recupera gli oggetti XmlSchema compilati per gli schemi del cliente e dell'indirizzo dal tipo XmlSchemaSet scorrendo la proprietà Schemas. Dal momento che gli schemi sono stati compilati, è possibile accedere alle proprietà del set PSCI (Post-Schema-Compilation-Infoset).

  3. Crea un oggetto XmlSchemaImport, imposta la proprietà Namespace dell'elemento import sullo spazio dei nomi dello schema dell'indirizzo, imposta la proprietà Schema dell'elemento import sull'oggetto XmlSchema dello schema dell'indirizzo e aggiunge l'elemento import alla proprietà Includes dello schema del cliente.

  4. Rielabora e compila l'oggetto modificato XmlSchema dello schema del cliente usando i metodi Reprocess e Compile della classe XmlSchemaSet e lo scrive nella console.

  5. Infine, usando la proprietà Includes dello schema del cliente, scrive in modo ricorsivo nella console tutti gli schemi importati nello schema del cliente. La proprietà Includes fornisce l'accesso a tutti gli elementi include, import o redefine aggiunti a uno schema.

Di seguito è riportato l'esempio di codice completo e gli schemi del cliente e dell'indirizzo scritti nella console.

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

Per altre informazioni sugli elementi <xs:import />, <xs:include /> e <xs:redefine /> e sulle classi XmlSchemaImport, XmlSchemaInclude e XmlSchemaRedefine, vedere il documento W3C XML Schema e la documentazione di riferimento sulle classi dello spazio dei nomi System.Xml.Schema.

Vedi anche