Przeczytaj w języku angielskim

Udostępnij za pośrednictwem


Uwzględnianie lub importowanie schematów XML

Schemat XML może zawierać <xs:import />elementy , <xs:include />i <xs:redefine /> . Te elementy schematu odnoszą się do innych schematów XML, które mogą służyć do uzupełnienia struktury schematu, który zawiera lub importuje je. XmlSchemaInclude Klasy XmlSchemaImport, i XmlSchemaRedefine mapować na te elementy w interfejsie API modelu obiektów schematu (SOM).

Dołączanie lub importowanie schematu XML

Poniższy przykład kodu uzupełnia schemat klienta utworzony w temacie Building XML Schemas (Tworzenie schematów XML) ze schematem adresu. Uzupełnienie schematu klienta przy użyciu schematu adresu sprawia, że typy adresów są dostępne w schemacie klienta.

Schemat adresu można włączyć przy użyciu elementów <xs:include /> lub <xs:import /> do używania składników schematu adresu zgodnie z rzeczywistym użyciem <xs:redefine /> lub za pomocą elementu w celu zmodyfikowania dowolnego z jego składników zgodnie z potrzebą schematu klienta. Ponieważ schemat adresu różni się targetNamespace od schematu klienta, <xs:import /> używany jest element i dlatego jest używany semantyka importu.

Przykładowy kod zawiera schemat adresu w poniższych krokach.

  1. Dodaje schemat klienta i schemat adresu do nowego XmlSchemaSet obiektu, a następnie je kompiluje. Wszystkie ostrzeżenia i błędy weryfikacji schematu napotkane podczas odczytywania lub kompilowania schematów są obsługiwane przez delegata ValidationEventHandler .

  2. Pobiera skompilowane XmlSchema obiekty zarówno dla schematów klienta, jak i adresów z XmlSchemaSet obiektu, iterując nad właściwością Schemas . Ponieważ schematy są kompilowane, dostępne są właściwości Post-Schema-Compilation-Infoset (PSCI).

  3. XmlSchemaImport Tworzy obiekt, ustawia Namespace właściwość importu do przestrzeni nazw schematu adresu, ustawia Schema właściwość importu do XmlSchema obiektu schematu adresu i dodaje import do Includes właściwości schematu klienta.

  4. Ponownie przetwarza i kompiluje zmodyfikowany XmlSchema obiekt schematu klienta przy użyciu Reprocess metod XmlSchemaSet i Compile klasy i i zapisuje go w konsoli programu .

  5. Na koniec cyklicznie zapisuje wszystkie schematy zaimportowane do schematu klienta do konsoli przy użyciu Includes właściwości schematu klienta. Właściwość Includes zapewnia dostęp do wszystkich elementów dołączania, importowania lub ponownego definiowania dodanych do schematu.

Poniżej przedstawiono kompletny przykład kodu oraz schematy klienta i adresów zapisane w konsoli programu .

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

Aby uzyskać więcej informacji na temat <xs:import />elementów , <xs:include />i oraz XmlSchemaImport<xs:redefine /> klas i XmlSchemaRedefine , XmlSchemaInclude zobacz dokumentację referencyjną klas XML W3C i dokumentację System.Xml.Schema dotyczącą klas przestrzeni nazw.

Zobacz też