Построение XML-схем

Обновлен: November 2007

Классы в пространстве имен System.Xml.Schema сопоставляются со структурами, определенными в рекомендациях по схемам XML консорциума W3C, и могут использоваться для сборки схем XML в памяти.

Построение схемы XML

В следующем примере кода для построения схемы XML в памяти используется API модели SOM.

Создание элемента и атрибутов

Примеры кода собирают пользовательскую схему снизу вверх, вначале создавая дочерние элементы, атрибуты и их соответствующие типы, а затем элементы верхнего уровня.

В следующем примере кода элементы FirstName и LastName, а также атрибут пользовательской схемы CustomerId создаются с помощью классов XmlSchemaElement и XmlSchemaAttribute модели SOM. Помимо свойств Name классов XmlSchemaElement и XmlSchemaAttribute, соответствующих атрибуту name элементов <xs:element /> и <xs:attribute /> схемы XML, все остальные атрибуты, разрешенные схемой (defaultValue, fixedValue, form и так далее), имеют соответствующие свойства в классах XmlSchemaElement и XmlSchemaAttribute.

' Create the FirstName and LastName elements.
Dim firstNameElement As XmlSchemaElement = New XmlSchemaElement()
firstNameElement.Name = "FirstName"
Dim lastNameElement As XmlSchemaElement = New XmlSchemaElement()
lastNameElement.Name = "LastName"

' Create CustomerId attribute.
Dim idAttribute As XmlSchemaAttribute = New XmlSchemaAttribute()
idAttribute.Name = "CustomerId"
idAttribute.Use = XmlSchemaUse.Required
// 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 FirstName and LastName elements.
        XmlSchemaElement^ firstNameElement = gcnew XmlSchemaElement();
        firstNameElement->Name = "FirstName";
        XmlSchemaElement^ lastNameElement = gcnew XmlSchemaElement();
        lastNameElement->Name = "LastName";

        // Create CustomerId attribute.
        XmlSchemaAttribute^ idAttribute = gcnew XmlSchemaAttribute();
        idAttribute->Name = "CustomerId";
        idAttribute->Use = XmlSchemaUse::Required;

Создание типов схемы

Содержимое элементов и атрибутов определяется их типом. Чтобы создать элементы и атрибуты со встроенными типами схемы, свойство SchemaTypeName классов XmlSchemaElement или XmlSchemaAttribute принимает значение соответствующего полного имени встроенного типа с помощью класса XmlQualifiedName. Чтобы создать определяемый пользователем тип для элементов и атрибутов, формируется новый простой или сложный тип с помощью классов XmlSchemaSimpleType или XmlSchemaComplexType.

efzwt1t0.alert_note(ru-ru,VS.90).gifПримечание.

Чтобы создать неименованные простые или сложные типы, являющиеся анонимными потомками элемента или атрибута (к атрибутам применяются только простые типы), присвойте свойству SchemaType класса XmlSchemaElement или класса XmlSchemaAttribute значение неименованного простого или сложного типа, а не свойства SchemaTypeName классов XmlSchemaElement или XmlSchemaAttribute.

Схемы XML допускают, чтобы анонимные и именованные простые типы выводились по ограничению из других простых типов (встроенных или пользовательских) либо конструировались в виде списка или объединения других простых типов. Класс XmlSchemaSimpleTypeRestriction используется для создания простого типа, ограничивая встроенный тип xs:string. Чтобы создать тип списка или объединения, можно также использовать класс XmlSchemaSimpleTypeList или XmlSchemaSimpleTypeUnion. Свойство XmlSchemaSimpleType.Content обозначает, является ли оно простым типом ограничения, типом списка или объединением.

В следующем примере кода тип FirstName элемента является встроенным типом xs:string, тип LastName — именованным простым типом, представляющим собой ограничение встроенного типа xs:string со значением аспекта MaxLength, равным 20, а тип атрибута CustomerId является встроенным типом xs:positiveInteger. Элемент Customer представляет собой анонимный сложный тип, примитив которого является последовательностью элементов FirstName и LastName и атрибут которого содержит атрибут CustomerId.

efzwt1t0.alert_note(ru-ru,VS.90).gifПримечание.

Классы XmlSchemaChoice и XmlSchemaAll можно также использовать в качестве примитивов сложного типа для репликации семантики <xs:choice /> или <xs:all />.

' Create the simple type for the LastName element.
Dim lastNameType As XmlSchemaSimpleType = New XmlSchemaSimpleType()
lastNameType.Name = "LastNameType"
Dim lastNameRestriction As XmlSchemaSimpleTypeRestriction = _
    New XmlSchemaSimpleTypeRestriction()
lastNameRestriction.BaseTypeName = _
    New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
Dim maxLength As XmlSchemaMaxLengthFacet = 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.
Dim customerElement As XmlSchemaElement = New XmlSchemaElement()
customerElement.Name = "Customer"

' Create an anonymous complex type for the Customer element.
Dim customerType As XmlSchemaComplexType = New XmlSchemaComplexType()
Dim sequence As XmlSchemaSequence = 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 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 the simple type for the LastName element.
XmlSchemaSimpleType^ lastNameType = gcnew XmlSchemaSimpleType();
lastNameType->Name = "LastNameType";
XmlSchemaSimpleTypeRestriction^ lastNameRestriction =
    gcnew XmlSchemaSimpleTypeRestriction();
lastNameRestriction->BaseTypeName =
    gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
XmlSchemaMaxLengthFacet^ maxLength = gcnew XmlSchemaMaxLengthFacet();
maxLength->Value = "20";
lastNameRestriction->Facets->Add(maxLength);
lastNameType->Content = lastNameRestriction;

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

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

// Create an anonymous complex type for the Customer element.
XmlSchemaComplexType^ customerType = gcnew XmlSchemaComplexType();
XmlSchemaSequence^ sequence = gcnew 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;

Создание и компиляция схем

В этой точке дочерние элементы и атрибуты, их соответствующие типы и элемент верхнего уровня Customer были созданы в памяти с помощью API модели SOM. В следующем примере кода с помощью класса XmlSchema создается элемент схемы, к нему добавляются элементы верхнего уровня и типы с помощью свойства XmlSchema.Items и полная схема компилируется с помощью класса XmlSchemaSet и выводится на консоль.

' Create an empty schema.
Dim customerSchema As XmlSchema = 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.
Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
AddHandler schemaSet.ValidationEventHandler, AddressOf ValidationCallback
schemaSet.Add(customerSchema)
schemaSet.Compile()

For Each schema As XmlSchema In schemaSet.Schemas()
    customerSchema = schema
Next

' Write the complete schema to the Console.
customerSchema.Write(Console.Out)
// 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);
// Create an empty schema.
XmlSchema^ customerSchema = gcnew 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 = gcnew XmlSchemaSet();
schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback);
schemaSet->Add(customerSchema);
schemaSet->Compile();

for each (XmlSchema^ schema in schemaSet->Schemas())
{
    customerSchema = schema;
}

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

Метод XmlSchemaSet.Compile проверяет пользовательскую схему по правилам схемы XML и делает доступными свойства результатов проверки компиляции схемы.

efzwt1t0.alert_note(ru-ru,VS.90).gifПримечание.

Все свойства результатов проверки компиляции схемы в API модели SOM отличаются от информационного набора окончательной проверки схемы.

Объект ValidationEventHandler, добавленный к набору XmlSchemaSet, является делегатом, вызывающим метод ответного вызова ValidationCallback для обработки ошибок и предупреждений проверки схемы.

Ниже приводится полный пример кода, а пользовательская схема выводится на консоль.

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

Class XmlSchemaCreateExample

    Shared Sub Main()

        ' Create the FirstName and LastName elements.
        Dim firstNameElement As XmlSchemaElement = New XmlSchemaElement()
        firstNameElement.Name = "FirstName"
        Dim lastNameElement As XmlSchemaElement = New XmlSchemaElement()
        lastNameElement.Name = "LastName"

        ' Create CustomerId attribute.
        Dim idAttribute As XmlSchemaAttribute = New XmlSchemaAttribute()
        idAttribute.Name = "CustomerId"
        idAttribute.Use = XmlSchemaUse.Required

        ' Create the simple type for the LastName element.
        Dim lastNameType As XmlSchemaSimpleType = New XmlSchemaSimpleType()
        lastNameType.Name = "LastNameType"
        Dim lastNameRestriction As XmlSchemaSimpleTypeRestriction = _
            New XmlSchemaSimpleTypeRestriction()
        lastNameRestriction.BaseTypeName = _
            New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
        Dim maxLength As XmlSchemaMaxLengthFacet = 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.
        Dim customerElement As XmlSchemaElement = New XmlSchemaElement()
        customerElement.Name = "Customer"

        ' Create an anonymous complex type for the Customer element.
        Dim customerType As XmlSchemaComplexType = New XmlSchemaComplexType()
        Dim sequence As XmlSchemaSequence = 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.
        Dim customerSchema As XmlSchema = 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.
        Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
        AddHandler schemaSet.ValidationEventHandler, AddressOf ValidationCallback
        schemaSet.Add(customerSchema)
        schemaSet.Compile()

        For Each schema As XmlSchema In schemaSet.Schemas()
            customerSchema = schema
        Next

        ' Write the complete schema to the Console.
        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 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);
    }
}
#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;

ref class XmlSchemaCreateExample
{
public:

    static void Main()
    {
        // Create the FirstName and LastName elements.
        XmlSchemaElement^ firstNameElement = gcnew XmlSchemaElement();
        firstNameElement->Name = "FirstName";
        XmlSchemaElement^ lastNameElement = gcnew XmlSchemaElement();
        lastNameElement->Name = "LastName";

        // Create CustomerId attribute.
        XmlSchemaAttribute^ idAttribute = gcnew XmlSchemaAttribute();
        idAttribute->Name = "CustomerId";
        idAttribute->Use = XmlSchemaUse::Required;

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

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

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

        // Create an anonymous complex type for the Customer element.
        XmlSchemaComplexType^ customerType = gcnew XmlSchemaComplexType();
        XmlSchemaSequence^ sequence = gcnew 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 = gcnew 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 = gcnew XmlSchemaSet();
        schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback);
        schemaSet->Add(customerSchema);
        schemaSet->Compile();

        for each (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);
    }
};

int main()
{
    XmlSchemaCreateExample::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: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>

См. также

Основные понятия

Общие сведения об модели объектов XML-схемы

Чтение и запись XML-схем

Обход XML-схем

Изменение XML-схем

Включение или импорт XML-схем

XmlSchemaSet для компиляции схемы

Набор сведений для постсхемной компиляции