Atravessando esquemas XML
Percorrer um esquema XML usando a API SOM (Schema Object Model) fornece acesso aos elementos, atributos e tipos armazenados no SOM. Percorrer um esquema XML carregado no SOM também é a primeira etapa na edição de um esquema XML usando a API do SOM.
Atravessando um esquema XML
As seguintes propriedades da XmlSchema classe fornecem acesso à coleção de todos os itens globais adicionados ao esquema XML.
Property | Tipo de objeto armazenado na coleção ou matriz |
---|---|
Elements | XmlSchemaElement |
Attributes | XmlSchemaAttribute |
AttributeGroups | XmlSchemaAttributeGroup |
Groups | XmlSchemaGroup |
Includes | XmlSchemaExternal, XmlSchemaInclude, XmlSchemaImport, ou XmlSchemaRedefine |
Items | XmlSchemaObject (fornece acesso a todos os elementos, atributos e tipos de nível global). |
Notations | XmlSchemaNotation |
SchemaTypes | XmlSchemaType, XmlSchemaSimpleType, XmlSchemaComplexType |
UnhandledAttributes | XmlAttribute (fornece acesso a atributos que não pertencem ao namespace do esquema) |
Nota
Todas as propriedades listadas na tabela acima, exceto a Items propriedade, são propriedades Post-Schema-Compilation-Infoset (PSCI) que não estão disponíveis até que o esquema tenha sido compilado. A Items propriedade é uma propriedade de pré-compilação de esquema que pode ser usada antes que o esquema tenha sido compilado para acessar e editar todos os elementos, atributos e tipos de nível global.
A UnhandledAttributes propriedade fornece acesso a todos os atributos que não pertencem ao namespace do esquema. Esses atributos não são processados pelo processador de esquema.
O exemplo de código a seguir demonstra a passagem pelo esquema do cliente criado no tópico Building XML Schemas . O exemplo de código demonstra percorrer o esquema usando as coleções descritas acima e grava todos os elementos e atributos no esquema no console.
O exemplo percorre o esquema do cliente nas etapas a seguir.
Adiciona o esquema do cliente a um novo XmlSchemaSet objeto e, em seguida, compila-o. Todos os avisos de validação de esquema e erros encontrados lendo ou compilando o esquema são manipulados pelo ValidationEventHandler delegado.
Recupera o objeto compilado XmlSchema do XmlSchemaSet iterando sobre a Schemas propriedade. Como o esquema é compilado, as propriedades Post-Schema-Compilation-Infoset (PSCI) são acessíveis.
Itera sobre cada XmlSchemaElement um na Values coleção da coleção post-schema-compilation XmlSchema.Elements gravando o nome de cada elemento no console.
Obtém o tipo complexo do
Customer
elemento usando a XmlSchemaComplexType classe.Se o tipo complexo tiver quaisquer atributos, obtém um para enumerar sobre cada XmlSchemaAttribute um IDictionaryEnumerator e grava seu nome no console.
Obtém a partícula de sequência do tipo complexo usando a XmlSchemaSequence classe.
Itera sobre cada XmlSchemaElement um na XmlSchemaSequence.Items coleção gravando o nome de cada elemento filho no console.
A seguir está o exemplo de código completo.
#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
A XmlSchemaElement.ElementSchemaType propriedade pode ser XmlSchemaSimpleType, ou XmlSchemaComplexType se for um tipo simples definido pelo usuário ou um tipo complexo. Também pode ser XmlSchemaDatatype se for um dos tipos de dados internos definidos na Recomendação de esquema XML do W3C. No esquema do cliente, o ElementSchemaType do elemento é XmlSchemaComplexType, e os FirstName
elementos e LastName
são XmlSchemaSimpleType.Customer
O exemplo de código no tópico Building XML Schemas usou a XmlSchemaComplexType.Attributes coleção para adicionar o atributo CustomerId
ao Customer
elemento . Esta é uma propriedade de pré-compilação de esquema. A propriedade Post-Schema-Compilation-Infoset correspondente é a XmlSchemaComplexType.AttributeUses coleção, que contém todos os atributos do tipo complexo, incluindo os que são herdados por meio da derivação de tipo.