Nota
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Recorrer un esquema XML utilizando la API del Modelo de Objetos de Esquema (SOM) ofrece acceso a los elementos, atributos y tipos almacenados en el SOM. Recorrer un esquema XML cargado en el SOM también es el primer paso para editar un esquema XML mediante la API del SOM.
Recorriendo un esquema XML
Las siguientes propiedades de la XmlSchema clase proporcionan acceso a la colección de todos los elementos globales agregados al esquema XML.
Propiedad | Tipo de objeto almacenado en la colección o matriz |
---|---|
Elements | XmlSchemaElement |
Attributes | XmlSchemaAttribute |
AttributeGroups | XmlSchemaAttributeGroup |
Groups | XmlSchemaGroup |
Includes | XmlSchemaExternal, XmlSchemaInclude, XmlSchemaImporto XmlSchemaRedefine |
Items | XmlSchemaObject (proporciona acceso a todos los elementos, atributos y tipos de nivel global). |
Notations | XmlSchemaNotation |
SchemaTypes | XmlSchemaType, , XmlSchemaSimpleType, XmlSchemaComplexType |
UnhandledAttributes | XmlAttribute (proporciona acceso a los atributos que no pertenecen al espacio de nombres de esquema) |
Nota:
Todas las propiedades enumeradas en la tabla anterior, excepto la Items propiedad , son propiedades Posteriores al esquema-Compilation-Infoset (PSCI) que no están disponibles hasta que se haya compilado el esquema. La propiedad Items es una propiedad de pre-compilación de esquema que se puede utilizar antes de que el esquema se haya compilado para acceder y editar todos los elementos, atributos y tipos de nivel global.
La UnhandledAttributes propiedad proporciona acceso a todos los atributos que no pertenecen al espacio de nombres de esquema. El procesador de esquemas no procesa estos atributos.
En el ejemplo de código siguiente se muestra cómo recorrer el esquema del cliente creado en el tema Building XML Schemas (Compilar esquemas XML ). En el ejemplo de código se muestra cómo recorrer el esquema mediante las colecciones descritas anteriormente y se escriben todos los elementos y atributos del esquema en la consola.
En el ejemplo se recorre el esquema del cliente en los pasos siguientes.
Agrega el esquema del cliente a un nuevo XmlSchemaSet objeto y, a continuación, lo compila. El delegado se encarga de manejar las advertencias y errores de validación de esquemas detectados al leer o compilar el esquema.
Recupera el objeto compilado XmlSchema de XmlSchemaSet mediante la iteración sobre la propiedad Schemas. Dado que el esquema está compilado, se puede acceder a las propiedades post-Schema-Compilation-Infoset (PSCI).
Recorre cada XmlSchemaElement en la colección Values de la colección XmlSchema.Elements posterior a la compilación de esquemas e imprime el nombre de cada elemento en la consola.
Obtiene el tipo complejo del
Customer
elemento mediante la XmlSchemaComplexType clase .Si el tipo complejo tiene algún atributo, obtiene un IDictionaryEnumerator para enumerar sobre cada XmlSchemaAttribute y luego escribe su nombre en la consola.
Obtiene la partícula de secuencia del tipo complejo mediante la XmlSchemaSequence clase .
Recorre en iteración cada XmlSchemaElement uno de la XmlSchemaSequence.Items colección escribiendo el nombre de cada elemento secundario en la consola.
A continuación se muestra el ejemplo de código completo.
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
La XmlSchemaElement.ElementSchemaType propiedad puede ser XmlSchemaSimpleType, o XmlSchemaComplexType si es un tipo simple definido por el usuario o un tipo complejo. También puede ser XmlSchemaDatatype si es uno de los tipos de datos integrados definidos en la recomendación de esquema XML de W3C. En el esquema del cliente, el ElementSchemaType del elemento Customer
es XmlSchemaComplexType, y los elementos FirstName
y LastName
son XmlSchemaSimpleType.
El ejemplo de código del tema Building XML Schemas (Compilar esquemas XML ) usó la XmlSchemaComplexType.Attributes colección para agregar el atributo CustomerId
al Customer
elemento . Esta es una propiedad de compilación previa de esquema. La propiedad correspondiente Post-Schema-Compilation-Infoset es la colección XmlSchemaComplexType.AttributeUses, que abarca todos los atributos del tipo complejo, incluyendo aquellos que se heredan a través de la derivación de tipos.