語言

遍歷 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、XmlSchemaSimpleType、XmlSchemaComplexType
UnhandledAttributes XmlAttribute (提供不屬於架構命名空間的屬性存取權)

備註

以上表格中列出的所有屬性,除了 Items 屬性之外,都是在編譯架構之前無法使用的 Post-Schema-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 架構建議中定義的其中一個內建資料類型,那麼也可以是 XmlSchemaDatatype。 在客戶架構中,ElementSchemaType 元素的 Customer 是 XmlSchemaComplexType,而 FirstName 和 LastName 元素為 XmlSchemaSimpleType。

建置 XML 架構主題中的程式碼範例會使用 XmlSchemaComplexType.Attributes 集合將 屬性CustomerId新增至 Customer 專案。 這是模式編譯前的屬性。 對應的 Post-Schema-Compilation-Infoset 屬性是 XmlSchemaComplexType.AttributeUses 集合,其中包含複雜型別的所有屬性,包括透過型別衍生繼承的屬性。

另請參閱