XML 스키마 통과

업데이트: November 2007

SOM(스키마 개체 모델) API를 사용하여 XML 스키마를 통과하면 SOM에 저장된 요소, 특성 및 형식에 액세스할 수 있습니다. SOM에 로드된 XML 스키마를 통과하는 것은 SOM API를 사용하여 XML 스키마를 편집하는 첫 번째 단계이기도 합니다.

XML 스키마 통과

다음 XmlSchema 클래스 속성에서는 XML 스키마에 추가된 모든 전역 항목의 컬렉션에 액세스할 수 있습니다.

속성

컬렉션 또는 배열에 저장된 개체 형식

Elements

XmlSchemaElement

Attributes

XmlSchemaAttribute

AttributeGroups

XmlSchemaAttributeGroup

Groups

XmlSchemaGroup

Includes

XmlSchemaExternal, XmlSchemaInclude, XmlSchemaImport 또는 XmlSchemaRedefine

Items

XmlSchemaObject(모든 전역 수준 요소, 특성 및 형식에 대한 액세스 제공)

Notations

XmlSchemaNotation

SchemaTypes

XmlSchemaType, XmlSchemaSimpleType, XmlSchemaComplexType

UnhandledAttributes

XmlAttribute(스키마 네임스페이스에 속하지 않은 특성에 대한 액세스 제공)

참고:

Items 속성을 제외하고 위의 표에 나열된 모든 속성은 스키마를 컴파일해야 사용할 수 있는 PSCI(Post-Schema-Compilation-Infoset) 속성입니다. Items 속성은 스키마를 컴파일하기 전에 모든 전역 수준 요소, 특성 및 형식에 액세스하여 이를 편집하는 데 사용할 수 있는 pre-schema-compilation 속성입니다.

UnhandledAttributes 속성은 스키마 네임스페이스에 속하지 않은 모든 특성에 대한 액세스를 제공합니다. 이러한 특성은 스키마 프로세서로 처리되지 않습니다.

다음 코드 예제에서는 XML 스키마 빌드 항목에서 만든 고객 스키마를 통과하는 것을 보여 줍니다. 이 코드 예제에서는 위에서 설명한 컬렉션을 사용하여 스키마를 통과하는 것을 보여 주고 스키마의 모든 요소와 특성을 콘솔에 작성합니다.

이 샘플은 다음과 같은 단계로 고객 스키마를 통과합니다.

  1. 고객 스키마를 새 XmlSchemaSet 개체에 추가한 다음 컴파일합니다. 스키마를 읽거나 컴파일할 때 발생하는 모든 스키마 유효성 검사 경고 및 오류는 ValidationEventHandler 대리자에서 처리됩니다.

  2. Schemas 속성을 반복하여 XmlSchemaSet에서 컴파일된 XmlSchema 개체를 검색합니다. 스키마가 컴파일되므로 PSCI(Post-Schema-Compilation-Infoset) 속성에 액세스할 수 있습니다.

  3. 각 요소 이름을 콘솔에 작성하는 post-schema-compilation XmlSchema.Elements 컬렉션의 Values 컬렉션에서 각 XmlSchemaElement를 반복합니다.

  4. XmlSchemaComplexType 클래스를 사용하여 Customer 요소의 복합 형식을 얻습니다.

  5. 복합 형식에 특성이 있을 경우 IDictionaryEnumerator가 각 XmlSchemaAttribute를 열거하도록 하고 그 이름을 콘솔에 작성합니다.

  6. XmlSchemaSequence 클래스를 사용하여 복합 형식의 sequence 파티클을 얻습니다.

  7. 각 자식 요소의 이름을 콘솔에 작성하는 XmlSchemaSequence.Items 컬렉션에서 각 XmlSchemaElement를 반복합니다.

다음은 전체 코드 예제입니다.

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

Class XmlSchemaTraverseExample

    Shared Sub Main()

        ' Add the customer schema to a new XmlSchemaSet and compile it.
        ' Any schema validation warnings and errors encountered reading or 
        ' compiling the schema 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.Compile()

        ' Retrieve the compiled XmlSchema object from the XmlSchemaSet
        ' by iterating over the Schemas property.
        Dim customerSchema As XmlSchema = Nothing
        For Each schema As XmlSchema In schemaSet.Schemas()
            customerSchema = schema
        Next

        ' Iterate over each XmlSchemaElement in the Values collection
        ' of the Elements property.
        For Each element As XmlSchemaElement In customerSchema.Elements.Values

            Console.WriteLine("Element: {0}", element.Name)

            ' Get the complex type of the Customer element.
            Dim complexType As XmlSchemaComplexType = CType(element.ElementSchemaType, XmlSchemaComplexType)

            ' If the complex type has any attributes, get an enumerator 
            ' and write each attribute name to the console.
            If complexType.AttributeUses.Count > 0 Then

                Dim enumerator As IDictionaryEnumerator = _
                    complexType.AttributeUses.GetEnumerator()

                While enumerator.MoveNext()

                    Dim attribute As XmlSchemaAttribute = _
                        CType(enumerator.Value, XmlSchemaAttribute)

                    Console.WriteLine("Attribute: {0}", Attribute.Name)
                End While
            End If

            ' Get the sequence particle of the complex type.
            Dim sequence As XmlSchemaSequence = CType(complexType.ContentTypeParticle, XmlSchemaSequence)

            For Each childElement As XmlSchemaElement In sequence.Items
                Console.WriteLine("Element: {0}", childElement.Name)
            Next
        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
using System;
using System.Collections;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaTraverseExample
{
    static void Main()
    {
        // Add the customer schema to a new XmlSchemaSet and compile it.
        // Any schema validation warnings and errors encountered reading or 
        // compiling the schema are handled by the ValidationEventHandler delegate.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add("http://www.tempuri.org", "customer.xsd");
        schemaSet.Compile();

        // Retrieve the compiled XmlSchema object from the XmlSchemaSet
        // by iterating over the Schemas property.
        XmlSchema customerSchema = null;
        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            customerSchema = schema;
        }

        // Iterate over each XmlSchemaElement in the Values collection
        // of the Elements property.
        foreach (XmlSchemaElement element in customerSchema.Elements.Values)
        {

            Console.WriteLine("Element: {0}", element.Name);

            // Get the complex type of the Customer element.
            XmlSchemaComplexType complexType = element.ElementSchemaType as XmlSchemaComplexType;

            // If the complex type has any attributes, get an enumerator 
            // and write each attribute name to the console.
            if (complexType.AttributeUses.Count > 0)
            {
                IDictionaryEnumerator enumerator =
                    complexType.AttributeUses.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    XmlSchemaAttribute attribute =
                        (XmlSchemaAttribute)enumerator.Value;

                    Console.WriteLine("Attribute: {0}", attribute.Name);
                }
            }

            // Get the sequence particle of the complex type.
            XmlSchemaSequence sequence = complexType.ContentTypeParticle as XmlSchemaSequence;

            // Iterate over each XmlSchemaElement in the Items collection.
            foreach (XmlSchemaElement childElement in sequence.Items)
            {
                Console.WriteLine("Element: {0}", childElement.Name);
            }
        }
    }

    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::Collections;
using namespace System::Xml;
using namespace System::Xml::Schema;

ref class XmlSchemaTraverseExample
{
public:

    static void Main()
    {
        // Add the customer schema to a new XmlSchemaSet and compile it.
        // Any schema validation warnings and errors encountered reading or 
        // compiling the schema are handled by the ValidationEventHandler delegate.
        XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet();
        schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback);
        schemaSet->Add("http://www.tempuri.org", "customer.xsd");
        schemaSet->Compile();

        // Retrieve the compiled XmlSchema object from the XmlSchemaSet
        // by iterating over the Schemas property.
        XmlSchema^ customerSchema = nullptr;
        for each (XmlSchema^ schema in schemaSet->Schemas())
        {
            customerSchema = schema;
        }

        // Iterate over each XmlSchemaElement in the Values collection
        // of the Elements property.
        for each (XmlSchemaElement^ element in customerSchema->Elements->Values)
        {

            Console::WriteLine("Element: {0}", element->Name);

            // Get the complex type of the Customer element.
            XmlSchemaComplexType^ complexType = dynamic_cast<XmlSchemaComplexType^>(element->ElementSchemaType);

            // If the complex type has any attributes, get an enumerator 
            // and write each attribute name to the console.
            if (complexType->AttributeUses->Count > 0)
            {
                IDictionaryEnumerator^ enumerator =
                    complexType->AttributeUses->GetEnumerator();

                while (enumerator->MoveNext())
                {
                    XmlSchemaAttribute^ attribute =
                        dynamic_cast<XmlSchemaAttribute^>(enumerator->Value);

                    Console::WriteLine("Attribute: {0}", attribute->Name);
                }
            }

            // Get the sequence particle of the complex type.
            XmlSchemaSequence^ sequence = dynamic_cast<XmlSchemaSequence^>(complexType->ContentTypeParticle);

            // Iterate over each XmlSchemaElement in the Items collection.
            for each (XmlSchemaElement^ childElement in sequence->Items)
            {
                Console::WriteLine("Element: {0}", childElement->Name);
            }
        }
    }

    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()
{
    XmlSchemaTraverseExample::Main();
    return 0;
};

XmlSchemaElement.ElementSchemaType 속성이 사용자 정의 단순 형식 또는 복합 형식인 경우 이 속성은 XmlSchemaSimpleType 또는 XmlSchemaComplexType일 수 있습니다. 또한 W3C XML 스키마 권장 사항에 정의된 기본 제공 데이터 형식 중 하나인 경우 XmlSchemaDatatype일 수도 있습니다. 고객 스키마에서 Customer 요소의 ElementSchemaTypeXmlSchemaComplexType이고 FirstName 및 LastName 요소는 XmlSchemaSimpleType입니다.

XML 스키마 빌드 항목의 코드 예제에서는 XmlSchemaComplexType.Attributes 컬렉션을 사용하여 Customer 요소에 CustomerId 특성을 추가했습니다. 이 속성은 pre-schema-compilation 속성입니다. 해당 Post-Schema-Compilation-Infoset 속성은 형식 파생을 통해 상속된 특성을 비롯하여 복합 형식의 모든 특성을 보유하는 XmlSchemaComplexType.AttributeUses 컬렉션입니다.

참고 항목

개념

XML 스키마 개체 모델 개요

XML 스키마 읽기 및 쓰기

XML 스키마 빌드

XML 스키마 편집

XML 스키마 포함하기 또는 가져오기

스키마 컴파일을 위한 XmlSchemaSet

Post-Schema Compilation Infoset