다음을 통해 공유


XML 스키마 트래버스

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, , XmlSchemaSimpleTypeXmlSchemaComplexType
UnhandledAttributes XmlAttribute (스키마 네임스페이스에 속하지 않는 특성에 대한 액세스를 제공합니다.)

비고

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

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

다음 코드 예제에서는 XML 스키마 빌드 항목에서 만든 고객 스키마를 트래버스하는 방법을 보여 줍니다. 코드 예제에서는 위에서 설명한 컬렉션을 사용하여 스키마를 트래버스하고 스키마의 모든 요소와 특성을 콘솔에 씁니다.

샘플은 다음 단계에서 고객 스키마를 트래버스합니다.

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

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

  3. 사후 스키마 컴파일 XmlSchemaElement 컬렉션의 Values 컬렉션에서 각 XmlSchema.Elements을(를) 순회하며 각 요소의 이름을 콘솔에 출력합니다.

  4. 클래스를 사용하여 Customer 요소의 복합 형식을 XmlSchemaComplexType에서 가져옵니다.

  5. 복합 형식에 특성이 있는 경우 각각 IDictionaryEnumerator 에 대해 열거할 값을 가져오 XmlSchemaAttribute 고 해당 이름을 콘솔에 씁니다.

  6. XmlSchemaSequence 클래스를 사용하여 복잡한 형식의 시퀀스 파티클을 가져옵니다.

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

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

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: {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: {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: {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);
    }
}
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

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

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

참고하십시오