更新:November 2007
使用架构对象模型 (SOM) API 遍历 XML 架构,可以访问 SOM 中存储的元素、属性和类型。 遍历加载到 SOM 的 XML 架构也是使用 SOM API 编辑 XML 架构的第一步。
遍历 XML 架构
使用 XmlSchema 类的下列属性可以访问添加到 XML 架构的所有全局项的集合。
| 属性 | 存储在集合或数组中的对象类型 | 
|---|---|
| XmlSchemaExternal、XmlSchemaInclude、XmlSchemaImport 或 XmlSchemaRedefine | |
| XmlSchemaObject(提供对所有全局级元素、属性和类型的访问) | |
| XmlAttribute(提供对不属于架构命名空间的属性的访问) | 
| .gif) 说明: | 
|---|
| 上表列出的所有属性(Items 属性除外)是后架构编译信息集 (PSCI) 属性,直到架构编译后才可用。 Items 属性是前架构编译属性,可以在架构编译之前使用,以访问和编辑所有全局级元素、属性和类型。 UnhandledAttributes 属性提供对不属于架构命名空间的所有属性的访问。 架构处理器不处理这些属性。 | 
后面的代码示例演示如何遍历生成 XML 架构主题中创建的客户架构。 代码示例演示如何使用上述集合遍历架构并将架构中的所有元素和属性写入控制台。
示例通过下列步骤遍历客户架构。
- 将客户架构添加到新的 XmlSchemaSet 对象并进行编译。 在读取或编译架构时遇到的任何架构验证警告和错误由 ValidationEventHandler 委托进行处理。 
- 通过循环访问 Schemas 属性,从 XmlSchemaSet 中检索已编译的 XmlSchema 对象。 因为架构已编译,所以,可以访问后架构编译信息集 (PSCI) 属性。 
- 在将每个元素的名称写入控制台的后架构编译 XmlSchema.Elements 集合的 Values 集合中循环访问每个 XmlSchemaElement。 
- 使用 XmlSchemaComplexType 类获取 Customer 元素的复杂类型。 
- 如果复杂类型具有任何属性,请获取 IDictionaryEnumerator 以循环访问每个 XmlSchemaAttribute 并将其名称写入控制台。 
- 使用 XmlSchemaSequence 类获取复杂类型的序列粒子。 
- 在将每个子元素的名称写入控制台的 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 元素的 ElementSchemaType 为 XmlSchemaComplexType,FirstName 和 LastName 元素为 XmlSchemaSimpleType。
生成 XML 架构 主题中的代码示例使用 XmlSchemaComplexType.Attributes 集合将属性 CustomerId 添加到 Customer 元素。 此属性是前架构编译属性。 对应的后架构编译信息集属性为 XmlSchemaComplexType.AttributeUses 集合,该集合包含复杂类型的所有属性,包括通过类型派生继承的属性。