Sdílet prostřednictvím


Procházení schémat XML

Procházení schématu XML pomocí rozhraní API modelu objektu schématu (SOM) poskytuje přístup k prvkům, atributům a typům uloženým v SOM. Procházení schématu XML načteného do SOM je také prvním krokem při úpravě schématu XML pomocí rozhraní SOM API.

Procházení schématu XML

Následující vlastnosti XmlSchema třídy poskytují přístup ke kolekci všech globálních položek přidaných do schématu XML.

Vlastnost Typ objektu uložený v kolekci nebo poli
Elements XmlSchemaElement
Attributes XmlSchemaAttribute
AttributeGroups XmlSchemaAttributeGroup
Groups XmlSchemaGroup
Includes XmlSchemaExternal, XmlSchemaInclude, XmlSchemaImportnebo XmlSchemaRedefine
Items XmlSchemaObject (poskytuje přístup ke všem prvkům, atributům a typům globální úrovně).
Notations XmlSchemaNotation
SchemaTypes XmlSchemaType, , XmlSchemaSimpleTypeXmlSchemaComplexType
UnhandledAttributes XmlAttribute (poskytuje přístup k atributům, které nepatří do oboru názvů schématu)

Poznámka:

Všechny vlastnosti uvedené v tabulce výše s výjimkou Items vlastnosti jsou vlastnosti PSCI (Post-Schema-Compilation-Infoset), které nejsou k dispozici, dokud nebude schéma zkompilováno. Vlastnost Items je předkompilační vlastnost, kterou lze použít před kompilací schématu, aby bylo možné získat přístup k prvkům, atributům a typům globální úrovně a upravovat je.

Vlastnost UnhandledAttributes poskytuje přístup ke všem atributům, které nepatří do oboru názvů schématu. Tyto atributy procesor schématu nezpracovávají.

Následující příklad kódu ukazuje procházení schématu zákazníka vytvořeného v tématu Vytváření schémat XML. Příklad kódu ukazuje procházení schématu pomocí výše popsaných kolekcí a zapíše všechny prvky a atributy ve schématu do konzoly.

Ukázka prochází schématem zákazníka v následujících krocích.

  1. Přidá schéma zákazníka do nového XmlSchemaSet objektu a pak ho zkompiluje. Delegát zpracovává všechna upozornění na ověření schématu a chyby, ke kterým došlo při čtení nebo kompilaci schématu ValidationEventHandler .

  2. Načte zkompilovaný XmlSchema objekt XmlSchemaSet iterací přes Schemas vlastnost. Vzhledem k tomu, že je schéma zkompilováno, jsou vlastnosti Post-Schema-Compilation-Infoset (PSCI) přístupné.

  3. Iteruje každý XmlSchemaElement v Values kolekci kolekce post-schema-kompilace zapisuje XmlSchema.Elements název každého prvku do konzoly.

  4. Získá komplexní typ elementu CustomerXmlSchemaComplexType pomocí třídy.

  5. Pokud má komplexní typ nějaké atributy, získá IDictionaryEnumerator výčet pro každý z nich XmlSchemaAttribute a zapíše jeho název do konzoly.

  6. Získá sekvenci částice komplexního typu pomocí XmlSchemaSequence třídy.

  7. Iteruje jednotlivé XmlSchemaElement prvky v XmlSchemaSequence.Items kolekci, které zapisují název každého podřízeného prvku do konzoly.

Následuje kompletní příklad kódu.

#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

Vlastnost XmlSchemaElement.ElementSchemaType může být XmlSchemaSimpleTypenebo XmlSchemaComplexType pokud se jedná o uživatelem definovaný jednoduchý typ nebo komplexní typ. Může to být XmlSchemaDatatype také v případě, že se jedná o jeden z předdefinovaných datových typů definovaných v doporučení schématu XML W3C. Ve schématu ElementSchemaTypeCustomer zákazníka je XmlSchemaComplexTypeprvek a FirstName prvky LastName jsou XmlSchemaSimpleType.

Příklad kódu v tématu Sestavení schémat XML použil XmlSchemaComplexType.Attributes kolekci k přidání atributu CustomerId do elementu Customer . Toto je vlastnost před kompilací schématu. Odpovídající Post-Schema-Compilation-Infoset vlastnost je XmlSchemaComplexType.AttributeUses kolekce, která obsahuje všechny atributy komplexního typu, včetně těch, které jsou zděděny prostřednictvím odvození typu.

Viz také