다음을 통해 공유


XML 스키마 빌드

네임스페이 System.Xml.Schema 스의 클래스는 W3C(World Wide Web 컨소시엄) XML 스키마 권장 사항에 정의된 구조에 매핑되며 메모리 내 XML 스키마를 빌드하는 데 사용할 수 있습니다.

XML 스키마 빌드

다음 코드 예제에서 SOM API는 고객 XML 스키마를 메모리 내 빌드하는 데 사용됩니다.

요소 및 특성 만들기

코드 예제에서는 아래에서부터 고객 스키마를 빌드하고 자식 요소, 특성 및 해당 형식을 먼저 만든 다음 최상위 요소를 만듭니다.

다음 코드 예제에서는 SOM의 FirstNameLastName 클래스를 사용하여 CustomerIdXmlSchemaElement 요소와 고객 스키마의 XmlSchemaAttribute 특성을 만듭니다. NameXmlSchemaElement 클래스의 속성은 XML 스키마의 XmlSchemaAttribute<xs:element /> 요소에서 "name" 특성에 해당하며, 스키마에서 허용하는 다른 모든 특성(<xs:attribute />, defaultValue, fixedValue 등)은 formXmlSchemaElement 클래스에 해당하는 속성을 가지고 있습니다.

// 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.
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

스키마 형식 만들기

요소 및 특성의 콘텐츠는 해당 형식에 의해 정의됩니다. 내장 스키마 형식 중 하나인 요소 및 특성을 만들기 위해 SchemaTypeName 또는 XmlSchemaElement 클래스의 XmlSchemaAttribute 속성은 XmlQualifiedName 클래스를 사용하여 내장 형식의 해당 정규화된 이름으로 설정됩니다. 사용자 정의 형식을 요소와 특성에 대해 정의하기 위해, XmlSchemaSimpleType 또는 XmlSchemaComplexType 클래스를 사용하여 새로운 단순 또는 복합 형식이 생성됩니다.

비고

요소 또는 특성의 익명 자식인 이름 없는 단순 또는 복합 형식을 만들려면(특성의 경우 단순 형식만 해당) 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 요소는 FirstNameLastName 요소의 시퀀스를 파티클로 하고, CustomerId 특성을 포함하는 익명 복합 형식입니다.

비고

또한 XmlSchemaChoice 또는 XmlSchemaAll 클래스를 복합 유형의 파티클로 사용하여 <xs:choice /> 또는 <xs:all />의 의미를 복제할 수 있습니다.

// 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.
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

스키마 만들기 및 컴파일

이 시점에서 자식 요소 및 특성, 해당 형식 및 최상위 Customer 요소는 SOM API를 사용하여 메모리 내 생성되었습니다. 다음 코드 예제에서 스키마 요소는 클래스를 사용하여 XmlSchema 만들어지고, 최상위 요소와 형식은 속성을 사용하여 XmlSchema.Items 추가되고, 전체 스키마는 클래스를 사용하여 XmlSchemaSet 컴파일되고 콘솔에 기록됩니다.

// 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.
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)

이 메서드는 XmlSchemaSet.Compile XML 스키마에 대한 규칙에 대해 고객 스키마의 유효성을 검사하고 스키마 컴파일 후 속성을 사용할 수 있도록 합니다.

비고

SOM API의 모든 사후 스키마 컴파일 속성은 Post-Schema-Validation-Infoset과 다릅니다.

ValidationEventHandlerXmlSchemaSet 에 추가된 것은 스키마 유효성 검사 경고 및 오류를 처리하기 위해 콜백 메서드 ValidationCallback 를 호출하는 대리자입니다.

다음은 전체 코드 예제이며 고객 스키마는 콘솔에 기록됩니다.

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

참고하십시오