次の方法で共有


XML スキーマを走査する

スキーマ オブジェクト モデル (SOM) API を使用して XML スキーマを走査すると、SOM に格納されている要素、属性、および型にアクセスできます。 SOM に読み込まれた XML スキーマの走査は、SOM API を使用して XML スキーマを編集する最初の手順でもあります。

XMLスキーマの解析

XmlSchema クラスの次のプロパティは、XML スキーマに追加されたすべてのグローバル項目のコレクションへのアクセスを提供します。

プロパティ コレクションまたは配列に格納されているオブジェクト型
Elements XmlSchemaElement
Attributes XmlSchemaAttribute
AttributeGroups XmlSchemaAttributeGroup
Groups XmlSchemaGroup
Includes XmlSchemaExternalXmlSchemaIncludeXmlSchemaImport、または XmlSchemaRedefine
Items XmlSchemaObject (すべてのグローバル レベルの要素、属性、および型へのアクセスを提供します)。
Notations XmlSchemaNotation
SchemaTypes XmlSchemaTypeXmlSchemaSimpleTypeXmlSchemaComplexType
UnhandledAttributes XmlAttribute (スキーマ名前空間に属していない属性へのアクセスを提供します)

Items プロパティを除く、上記の表に示されているすべてのプロパティは、スキーマがコンパイルされるまで使用できないポスト スキーマCompilation-Infoset (PSCI) プロパティです。 Items プロパティは、スキーマがコンパイルされる前に、グローバル レベルのすべての要素、属性、および型にアクセスして編集するために使用できる、スキーマコンパイル前のプロパティです。

UnhandledAttributes プロパティは、スキーマ名前空間に属していないすべての属性へのアクセスを提供します。 これらの属性は、スキーマ プロセッサによって処理されません。

次のコード例では、「XML スキーマの構築」トピックで作成した顧客 スキーマの走査を 示します。 このコード例では、上記のコレクションを使用してスキーマを走査し、スキーマ内のすべての要素と属性をコンソールに書き込む方法を示します。

このサンプルでは、次の手順で顧客スキーマを走査します。

  1. 顧客スキーマを新しい XmlSchemaSet オブジェクトに追加し、コンパイルします。 スキーマ検証の警告と、スキーマの読み取りまたはコンパイルで発生したエラーは、 ValidationEventHandler デリゲートによって処理されます。

  2. XmlSchema プロパティを反復処理して、コンパイル済みのXmlSchemaSet オブジェクトをSchemasから取得します。 スキーマがコンパイルされているため、ポストスキーマCompilation-Infoset (PSCI) プロパティにアクセスできます。

  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 スキーマの推奨事項で定義されている組み込みデータ型の 1 つである場合は、 XmlSchemaDatatype することもできます。 顧客スキーマでは、ElementSchemaType要素のCustomerXmlSchemaComplexTypeされ、FirstName要素とLastName要素がXmlSchemaSimpleTypeされます。

XML スキーマの構築 」トピックのコード例では、 XmlSchemaComplexType.Attributes コレクションを使用して、属性 CustomerIdCustomer 要素に追加しました。 これは、スキーマコンパイル前のプロパティです。 対応する Post-Schema-Compilation-Infoset プロパティは、複合型のすべての属性 (型派生によって継承されたものを含む) を保持する XmlSchemaComplexType.AttributeUses コレクションです。

こちらも参照ください