Udostępnij za pośrednictwem


Przechodzenie schematów XML

Przechodzenie schematu XML przy użyciu interfejsu API modelu obiektów schematu (SOM) zapewnia dostęp do elementów, atrybutów i typów przechowywanych w som. Przechodzenie schematu XML załadowanego do som jest również pierwszym krokiem edytowania schematu XML przy użyciu interfejsu API SOM.

Przechodzenie schematu XML

Następujące właściwości XmlSchema klasy zapewniają dostęp do kolekcji wszystkich elementów globalnych dodanych do schematu XML.

Właściwości Typ obiektu przechowywany w kolekcji lub tablicy
Elements XmlSchemaElement
Attributes XmlSchemaAttribute
AttributeGroups XmlSchemaAttributeGroup
Groups XmlSchemaGroup
Includes XmlSchemaExternal, XmlSchemaInclude, lub XmlSchemaImportXmlSchemaRedefine
Items XmlSchemaObject (zapewnia dostęp do wszystkich elementów, atrybutów i typów na poziomie globalnym).
Notations XmlSchemaNotation
SchemaTypes XmlSchemaType, , XmlSchemaSimpleTypeXmlSchemaComplexType
UnhandledAttributes XmlAttribute (zapewnia dostęp do atrybutów, które nie należą do przestrzeni nazw schematu)

Uwaga

Wszystkie właściwości wymienione w powyższej tabeli, z wyjątkiem Items właściwości, to właściwości Post-Schema-Compilation-Infoset (PSCI), które nie są dostępne, dopóki schemat nie zostanie skompilowany. Właściwość Items jest właściwością kompilacji przed schematem, która może być używana przed skompilowanym schematem w celu uzyskania dostępu do wszystkich elementów, atrybutów i typów na poziomie globalnym oraz edytowania ich.

Właściwość UnhandledAttributes zapewnia dostęp do wszystkich atrybutów, które nie należą do przestrzeni nazw schematu. Te atrybuty nie są przetwarzane przez procesor schematu.

Poniższy przykład kodu pokazuje przechodzenie schematu klienta utworzonego w temacie Building XML Schemas (Tworzenie schematów XML). W przykładzie kodu pokazano przechodzenie schematu przy użyciu kolekcji opisanych powyżej i zapisuje wszystkie elementy i atrybuty w schemacie w konsoli programu .

Przykład przechodzi przez schemat klienta w poniższych krokach.

  1. Dodaje schemat klienta do nowego XmlSchemaSet obiektu, a następnie kompiluje go. Wszystkie ostrzeżenia i błędy weryfikacji schematu napotkane podczas odczytywania lub kompilowania schematu są obsługiwane przez delegata ValidationEventHandler .

  2. Pobiera skompilowany XmlSchema obiekt z XmlSchemaSet obiektu, iterując nad właściwością Schemas . Ponieważ schemat jest kompilowany, właściwości Post-Schema-Compilation-Infoset (PSCI) są dostępne.

  3. Iteruje każdą XmlSchemaElement z nich w Values kolekcji po kompilacji XmlSchema.Elements schematu, pisząc nazwę każdego elementu do konsoli.

  4. Pobiera typ Customer złożony elementu przy użyciu XmlSchemaComplexType klasy .

  5. Jeśli typ złożony ma jakiekolwiek atrybuty, pobiera element IDictionaryEnumerator do wyliczenia dla każdej XmlSchemaAttribute z nich i zapisuje jego nazwę w konsoli.

  6. Pobiera cząstkę sekwencji typu złożonego przy użyciu XmlSchemaSequence klasy .

  7. Iteruje poszczególne XmlSchemaElement elementy w XmlSchemaSequence.Items kolekcji zapisują nazwę każdego elementu podrzędnego w konsoli programu .

Poniżej przedstawiono kompletny przykład kodu.

#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;
};
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);
    }
}
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

Właściwość XmlSchemaElement.ElementSchemaType może mieć XmlSchemaSimpleTypewartość , lub XmlSchemaComplexType jeśli jest to typ prosty zdefiniowany przez użytkownika lub typ złożony. Może to być XmlSchemaDatatype również, jeśli jest to jeden z wbudowanych typów danych zdefiniowanych w rekomendacji schematu XML W3C. W schemacie klienta element ElementSchemaTypeCustomer to XmlSchemaComplexType, a FirstName elementy i LastName to XmlSchemaSimpleType.

Przykład kodu w temacie Building XML Schemas (Kompilowanie schematów XML) używa XmlSchemaComplexType.Attributes kolekcji w celu dodania atrybutu CustomerIdCustomer do elementu . Jest to właściwość przed kompilacją schematu. Odpowiadająca właściwość Post-Schema-Compilation-Infoset to XmlSchemaComplexType.AttributeUses kolekcja zawierająca wszystkie atrybuty typu złożonego, w tym te, które są dziedziczone za pośrednictwem wyprowadzenia typu.

Zobacz też