Dela via


Bläddra i XML-scheman

Genom att bläddra i ett XML-schema med hjälp av API:et Schema Object Model (SOM) får du åtkomst till de element, attribut och typer som lagras i SOM. Att bläddra i ett XML-schema som lästs in i SOM är också det första steget i att redigera ett XML-schema med SOM-API:et.

Bläddra i ett XML-schema

Följande egenskaper för klassen XmlSchema ger åtkomst till samlingen med alla globala objekt som har lagts till i XML-schemat.

Fastighet Objekttyp som lagras i samlingen eller matrisen
Elements XmlSchemaElement
Attributes XmlSchemaAttribute
AttributeGroups XmlSchemaAttributeGroup
Groups XmlSchemaGroup
Includes XmlSchemaExternal, XmlSchemaInclude, XmlSchemaImporteller XmlSchemaRedefine
Items XmlSchemaObject (ger åtkomst till alla element, attribut och typer på global nivå).
Notations XmlSchemaNotation
SchemaTypes XmlSchemaType, , XmlSchemaSimpleTypeXmlSchemaComplexType
UnhandledAttributes XmlAttribute (ger åtkomst till attribut som inte tillhör schemanamnområdet)

Anmärkning

Alla egenskaper som anges i tabellen ovan, förutom egenskapen Items, är PSCI-egenskaper (Post-Schema-Compilation-Infoset) som inte är tillgängliga förrän schemat har kompilerats. Egenskapen Items är en förschemakompileringsegenskap som kan användas innan schemat har kompilerats för att komma åt och redigera alla element, attribut och typer på global nivå.

Egenskapen UnhandledAttributes ger åtkomst till alla attribut som inte tillhör schemanamnområdet. Dessa attribut bearbetas inte av schemaprocessorn.

Kodexemplet som följer visar hur du går igenom kundschemat som skapades i avsnittet Skapa XML-scheman . Kodexemplet visar hur du passerar schemat med hjälp av samlingarna som beskrivs ovan och skriver alla element och attribut i schemat till konsolen.

Exemplet går igenom kundschemat i följande steg.

  1. Lägger till kundschemat i ett nytt XmlSchemaSet objekt och kompilerar det sedan. Eventuella schemavalideringsvarningar och fel som påträffades när schemat lästes eller kompilerades hanteras av ValidationEventHandler ombud.

  2. Hämtar det kompilerade XmlSchema-objektet från XmlSchemaSet genom att iterera över egenskapen Schemas. Eftersom schemat kompileras är PSCI-egenskaper (Post-Schema-Compilation-Infoset) tillgängliga.

  3. Itererar över varje XmlSchemaElement i Values-samlingen av samlingen XmlSchema.Elements efter schemakompilering och skriver namnet på varje element till konsolen.

  4. Hämtar den komplexa typen av Customer-element med hjälp av klassen XmlSchemaComplexType.

  5. Om den komplexa typen har några attribut hämtas en IDictionaryEnumerator för att enumerera över varje XmlSchemaAttribute och dess namn skrivs ut till konsolen.

  6. Hämtar sekvenspartikeln av den komplexa typen med hjälp av klassen XmlSchemaSequence.

  7. Itererar över varje XmlSchemaElement i XmlSchemaSequence.Items-samlingen och skriver ut namnet på varje barnelement till konsolen.

Följande är det fullständiga kodexemplet.

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

Egenskapen XmlSchemaElement.ElementSchemaType kan vara XmlSchemaSimpleTypeeller XmlSchemaComplexType om den är en användardefinierad enkel typ eller en komplex typ. Det kan också vara XmlSchemaDatatype om det är en av de inbyggda datatyperna som definieras i W3C XML-schemarekommendering. I kundschemat är ElementSchemaType för elementet CustomerXmlSchemaComplexTypeoch elementen FirstName och LastNameXmlSchemaSimpleType.

Kodexemplet i avsnittet Skapa XML-scheman använde XmlSchemaComplexType.Attributes samlingen för att lägga till attributet CustomerId i elementet Customer . Det här är en egenskap för förschemakompilering. Motsvarande Post-Schema-Compilation-Infoset-egenskapen är XmlSchemaComplexType.AttributeUses-samlingen, som innehåller alla attribut för den komplexa typen, inklusive dem som ärvs genom typderivering.

Se även