Przeczytaj w języku angielskim

Udostępnij za pośrednictwem


Tworzenie schematów XML

Klasy w System.Xml.Schema przestrzeni nazw są mapowane na struktury zdefiniowane w rekomendacji schematu XML World Wide Web Consortium (W3C) i mogą służyć do kompilowania schematów XML w pamięci.

Tworzenie schematu XML

W poniższych przykładach kodu interfejs API SOM jest używany do tworzenia schematu XML klienta w pamięci.

Tworzenie elementu i atrybutów

Przykłady kodu tworzą schemat klienta od dołu, tworząc najpierw elementy podrzędne, atrybuty i odpowiadające im typy, a następnie elementy najwyższego poziomu.

W poniższym przykładzie FirstName kodu elementy i LastName , a także CustomerId atrybut schematu klienta są tworzone przy użyciu XmlSchemaElement klas i XmlSchemaAttribute SOM. Name Oprócz właściwości XmlSchemaElement klas iXmlSchemaAttribute, które odpowiadają atrybutowi <xs:element /> "name" elementów i <xs:attribute /> w schemacie XML, wszystkie inne atrybuty dozwolone przez schemat (defaultValue, fixedValue, formitd.) mają odpowiednie właściwości w XmlSchemaElement klasach i XmlSchemaAttribute .

C#
// Create the FirstName and LastName elements.
XmlSchemaElement firstNameElement = new XmlSchemaElement();
firstNameElement.Name = "FirstName";
XmlSchemaElement lastNameElement = new XmlSchemaElement();
lastNameElement.Name = "LastName";

// Create CustomerId attribute.
XmlSchemaAttribute idAttribute = new XmlSchemaAttribute();
idAttribute.Name = "CustomerId";
idAttribute.Use = XmlSchemaUse.Required;

Tworzenie typów schematów

Zawartość elementów i atrybutów jest definiowana przez ich typy. Aby utworzyć elementy i atrybuty, których typy są jednym z wbudowanych typów schematów, SchemaTypeName właściwość klasy lub XmlSchemaAttribute jest ustawiana z odpowiednią kwalifikowaną nazwą typu wbudowanego XmlQualifiedNameXmlSchemaElement przy użyciu klasy. Aby utworzyć typ zdefiniowany przez użytkownika dla elementów i atrybutów, tworzony jest nowy prosty lub złożony typ przy użyciu XmlSchemaSimpleType klasy lub XmlSchemaComplexType .

Uwaga

Aby utworzyć nienazwane proste lub złożone typy, które są anonimową częścią podrzędną elementu lub atrybutu (mają zastosowanie tylko proste typy dla atrybutów), ustaw SchemaType właściwość klas lub XmlSchemaAttribute na nienazwany prosty lub złożony typ, zamiast SchemaTypeName właściwości XmlSchemaElement klas lub XmlSchemaAttributeXmlSchemaElement.

Schematy XML umożliwiają uzyskanie zarówno anonimowych, jak i nazwanych prostych typów przez ograniczenie innych typów prostych (wbudowanych lub zdefiniowanych przez użytkownika) lub skonstruowanych jako lista lub związek innych typów prostych. Klasa XmlSchemaSimpleTypeRestriction służy do tworzenia prostego typu przez ograniczenie typu wbudowanego xs:string . Można również użyć XmlSchemaSimpleTypeList klas lub XmlSchemaSimpleTypeUnion , aby utworzyć typy list lub unii. Właściwość XmlSchemaSimpleType.Content określa, czy jest to proste ograniczenie typu, lista, czy unia.

W poniższym przykładzie FirstName kodu typ elementu jest typem xs:stringwbudowanym , LastName typ elementu jest typem prostym o nazwie , który jest ograniczeniem typu wbudowanego xs:string, z wartością MaxLength aspektu 20, a CustomerId typ atrybutu jest typem wbudowanym xs:positiveInteger. Element Customer jest anonimowym typem złożonym, którego cząstka jest sekwencją FirstName elementów i LastName , których atrybuty zawierają CustomerId atrybut .

Uwaga

Można również użyć XmlSchemaChoice klas lub XmlSchemaAll jako cząstki typu złożonego do replikacji <xs:choice /> lub <xs:all /> semantyki.

C#
// Create the simple type for the LastName element.
XmlSchemaSimpleType lastNameType = new XmlSchemaSimpleType();
lastNameType.Name = "LastNameType";
XmlSchemaSimpleTypeRestriction lastNameRestriction =
    new XmlSchemaSimpleTypeRestriction();
lastNameRestriction.BaseTypeName =
    new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
XmlSchemaMaxLengthFacet maxLength = new XmlSchemaMaxLengthFacet();
maxLength.Value = "20";
lastNameRestriction.Facets.Add(maxLength);
lastNameType.Content = lastNameRestriction;

// Associate the elements and attributes with their types.
// Built-in type.
firstNameElement.SchemaTypeName =
    new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
// User-defined type.
lastNameElement.SchemaTypeName =
    new XmlQualifiedName("LastNameType", "http://www.tempuri.org");
// Built-in type.
idAttribute.SchemaTypeName = new XmlQualifiedName("positiveInteger",
    "http://www.w3.org/2001/XMLSchema");

// Create the top-level Customer element.
XmlSchemaElement customerElement = new XmlSchemaElement();
customerElement.Name = "Customer";

// Create an anonymous complex type for the Customer element.
XmlSchemaComplexType customerType = new XmlSchemaComplexType();
XmlSchemaSequence sequence = new XmlSchemaSequence();
sequence.Items.Add(firstNameElement);
sequence.Items.Add(lastNameElement);
customerType.Particle = sequence;

// Add the CustomerId attribute to the complex type.
customerType.Attributes.Add(idAttribute);

// Set the SchemaType of the Customer element to
// the anonymous complex type created above.
customerElement.SchemaType = customerType;

Tworzenie i kompilowanie schematów

W tym momencie elementy podrzędne i atrybuty, odpowiadające im typy i element najwyższego poziomu Customer zostały utworzone w pamięci przy użyciu interfejsu API SOM. W poniższym przykładzie kodu element schematu jest tworzony przy użyciu XmlSchema klasy, do niego dodawane są elementy i typy najwyższego poziomu przy użyciu właściwości, a kompletny schemat jest kompilowany przy użyciu XmlSchema.ItemsXmlSchemaSet klasy i zapisywany w konsoli.

C#
// Create an empty schema.
XmlSchema customerSchema = new XmlSchema();
customerSchema.TargetNamespace = "http://www.tempuri.org";

// Add all top-level element and types to the schema
customerSchema.Items.Add(customerElement);
customerSchema.Items.Add(lastNameType);

// Create an XmlSchemaSet to compile the customer schema.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
schemaSet.Add(customerSchema);
schemaSet.Compile();

foreach (XmlSchema schema in schemaSet.Schemas())
{
    customerSchema = schema;
}

// Write the complete schema to the Console.
customerSchema.Write(Console.Out);

Metoda XmlSchemaSet.Compile weryfikuje schemat klienta względem reguł schematu XML i udostępnia właściwości kompilacji po schemacie.

Uwaga

Wszystkie właściwości po kompilacji schematu w interfejsie API SOM różnią się od zestawu Post-Schema-Validation-Infoset.

Element ValidationEventHandler dodany do elementu XmlSchemaSet to delegat, który wywołuje metodę ValidationCallback wywołania zwrotnego w celu obsługi ostrzeżeń i błędów weryfikacji schematu.

Poniżej przedstawiono kompletny przykład kodu i schemat klienta zapisany w konsoli programu .

C#
using System;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaCreateExample
{
    static void Main(string[] args)
    {
        // Create the FirstName and LastName elements.
        XmlSchemaElement firstNameElement = new XmlSchemaElement();
        firstNameElement.Name = "FirstName";
        XmlSchemaElement lastNameElement = new XmlSchemaElement();
        lastNameElement.Name = "LastName";

        // Create CustomerId attribute.
        XmlSchemaAttribute idAttribute = new XmlSchemaAttribute();
        idAttribute.Name = "CustomerId";
        idAttribute.Use = XmlSchemaUse.Required;

        // Create the simple type for the LastName element.
        XmlSchemaSimpleType lastNameType = new XmlSchemaSimpleType();
        lastNameType.Name = "LastNameType";
        XmlSchemaSimpleTypeRestriction lastNameRestriction =
            new XmlSchemaSimpleTypeRestriction();
        lastNameRestriction.BaseTypeName =
            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        XmlSchemaMaxLengthFacet maxLength = new XmlSchemaMaxLengthFacet();
        maxLength.Value = "20";
        lastNameRestriction.Facets.Add(maxLength);
        lastNameType.Content = lastNameRestriction;

        // Associate the elements and attributes with their types.
        // Built-in type.
        firstNameElement.SchemaTypeName =
            new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
        // User-defined type.
        lastNameElement.SchemaTypeName =
            new XmlQualifiedName("LastNameType", "http://www.tempuri.org");
        // Built-in type.
        idAttribute.SchemaTypeName = new XmlQualifiedName("positiveInteger",
            "http://www.w3.org/2001/XMLSchema");

        // Create the top-level Customer element.
        XmlSchemaElement customerElement = new XmlSchemaElement();
        customerElement.Name = "Customer";

        // Create an anonymous complex type for the Customer element.
        XmlSchemaComplexType customerType = new XmlSchemaComplexType();
        XmlSchemaSequence sequence = new XmlSchemaSequence();
        sequence.Items.Add(firstNameElement);
        sequence.Items.Add(lastNameElement);
        customerType.Particle = sequence;

        // Add the CustomerId attribute to the complex type.
        customerType.Attributes.Add(idAttribute);

        // Set the SchemaType of the Customer element to
        // the anonymous complex type created above.
        customerElement.SchemaType = customerType;

        // Create an empty schema.
        XmlSchema customerSchema = new XmlSchema();
        customerSchema.TargetNamespace = "http://www.tempuri.org";

        // Add all top-level element and types to the schema
        customerSchema.Items.Add(customerElement);
        customerSchema.Items.Add(lastNameType);

        // Create an XmlSchemaSet to compile the customer schema.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add(customerSchema);
        schemaSet.Compile();

        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            customerSchema = schema;
        }

        // Write the complete schema to the Console.
        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);
    }
}
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: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>  

Zobacz też