Compilando esquemas XML
As classes no namespace System.Xml.Schema mapeiam para as estruturas definidas na recomendação do W3C (World Wide Web Consortium) sobre esquemas XML e podem ser usadas para compilar esquemas XML na memória.
Compilando um esquema XML
Nos exemplos de código a seguir, a API do SOM é usada para compilar um esquema XML cliente na memória.
Criando o elemento e os atributos
Os exemplos de código compilam o esquema cliente de baixo para cima, criando primeiro elementos e atributos filho, bem como seus tipos correspondentes, e depois os elementos de nível superior.
No exemplo de código a seguir, os elementos FirstName
e LastName
, bem como o atributo CustomerId
do esquema cliente são criados usando as classes XmlSchemaElement e XmlSchemaAttribute do SOM. Com exceção das propriedades Name das classes XmlSchemaElement e XmlSchemaAttribute, que correspondem ao atributo "name" dos elementos <xs:element />
e <xs:attribute />
em um esquema XML, todos os outros atributos permitidos pelo esquema (defaultValue
, fixedValue
, form
e assim por diante) têm propriedades correspondentes nas classes XmlSchemaElement e XmlSchemaAttribute.
// Create the FirstName and LastName elements.
XmlSchemaElement^ firstNameElement = gcnew XmlSchemaElement();
firstNameElement->Name = "FirstName";
XmlSchemaElement^ lastNameElement = gcnew XmlSchemaElement();
lastNameElement->Name = "LastName";
// Create CustomerId attribute.
XmlSchemaAttribute^ idAttribute = gcnew XmlSchemaAttribute();
idAttribute->Name = "CustomerId";
idAttribute->Use = XmlSchemaUse::Required;
// Create the FirstName and LastName elements.
XmlSchemaElement firstNameElement = new XmlSchemaElement();
firstNameElement.Name = "FirstName";
XmlSchemaElement lastNameElement = new XmlSchemaElement();
lastNameElement.Name = "LastName";
// Create CustomerId attribute.
XmlSchemaAttribute idAttribute = new XmlSchemaAttribute();
idAttribute.Name = "CustomerId";
idAttribute.Use = XmlSchemaUse.Required;
' Create the FirstName and LastName elements.
Dim firstNameElement As XmlSchemaElement = New XmlSchemaElement()
firstNameElement.Name = "FirstName"
Dim lastNameElement As XmlSchemaElement = New XmlSchemaElement()
lastNameElement.Name = "LastName"
' Create CustomerId attribute.
Dim idAttribute As XmlSchemaAttribute = New XmlSchemaAttribute()
idAttribute.Name = "CustomerId"
idAttribute.Use = XmlSchemaUse.Required
Criando tipos de esquema
O conteúdo de elementos e de atributos é definido pelos respectivos tipos. Para criar elementos e atributos cujos tipos são um dos tipos internos do esquema, a propriedade SchemaTypeName das classes XmlSchemaElement ou XmlSchemaAttribute são definidas com o nome qualificado correspondente do tipo interno usando a classe XmlQualifiedName. Para criar um tipo definido pelo usuário de elementos e atributos, um novo tipo simples ou complexo é criado usando a classe XmlSchemaSimpleType ou XmlSchemaComplexType.
Observação
Para criar tipos simples ou complexos sem nome que sejam filhos anônimos de um elemento ou atributo (somente os tipos simples são aplicáveis a atributos), defina a propriedade SchemaType das classes XmlSchemaElement ou XmlSchemaAttribute como o tipo simples ou complexo sem nome, em vez da propriedade SchemaTypeName das classes XmlSchemaElement ou XmlSchemaAttribute.
Os esquemas XML permitem que tipos simples, anônimos e nomeados, sejam derivados pela restrição de outros tipos simples (internos ou definidos pelo usuário) ou construídos como uma lista ou união de outros tipos simples. A classe XmlSchemaSimpleTypeRestriction é usada para criar um tipo simples restringindo o tipo interno xs:string
. Você também pode usar as classes XmlSchemaSimpleTypeList ou XmlSchemaSimpleTypeUnion para criar tipos de lista ou de união. A propriedade XmlSchemaSimpleType.Content indica se é uma união, uma lista ou uma restrição de tipos simples.
No exemplo de código a seguir, o tipo do elemento FirstName
é o tipo interno xs:string
, o tipo do elemento LastName
é um tipo simples nomeado que é uma restrição do tipo interno xs:string
, com um valor de faceta MaxLength
igual a 20, e o tipo do atributo CustomerId
é o tipo interno xs:positiveInteger
. O elemento Customer
é um tipo complexo anônimo cuja partícula é a sequência dos elementos FirstName
e LastName
e cujos atributos contêm o atributo CustomerId
.
Observação
Você também pode usar as classes XmlSchemaChoice ou XmlSchemaAll como partícula do tipo complexo para replicar as semânticas <xs:choice />
ou <xs:all />
.
// Create the simple type for the LastName element.
XmlSchemaSimpleType^ lastNameType = gcnew XmlSchemaSimpleType();
lastNameType->Name = "LastNameType";
XmlSchemaSimpleTypeRestriction^ lastNameRestriction =
gcnew XmlSchemaSimpleTypeRestriction();
lastNameRestriction->BaseTypeName =
gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
XmlSchemaMaxLengthFacet^ maxLength = gcnew XmlSchemaMaxLengthFacet();
maxLength->Value = "20";
lastNameRestriction->Facets->Add(maxLength);
lastNameType->Content = lastNameRestriction;
// Associate the elements and attributes with their types.
// Built-in type.
firstNameElement->SchemaTypeName =
gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
// User-defined type.
lastNameElement->SchemaTypeName =
gcnew XmlQualifiedName("LastNameType", "http://www.tempuri.org");
// Built-in type.
idAttribute->SchemaTypeName = gcnew XmlQualifiedName("positiveInteger",
"http://www.w3.org/2001/XMLSchema");
// Create the top-level Customer element.
XmlSchemaElement^ customerElement = gcnew XmlSchemaElement();
customerElement->Name = "Customer";
// Create an anonymous complex type for the Customer element.
XmlSchemaComplexType^ customerType = gcnew XmlSchemaComplexType();
XmlSchemaSequence^ sequence = gcnew XmlSchemaSequence();
sequence->Items->Add(firstNameElement);
sequence->Items->Add(lastNameElement);
customerType->Particle = sequence;
// Add the CustomerId attribute to the complex type.
customerType->Attributes->Add(idAttribute);
// Set the SchemaType of the Customer element to
// the anonymous complex type created above.
customerElement->SchemaType = customerType;
// Create the simple type for the LastName element.
XmlSchemaSimpleType lastNameType = new XmlSchemaSimpleType();
lastNameType.Name = "LastNameType";
XmlSchemaSimpleTypeRestriction lastNameRestriction =
new XmlSchemaSimpleTypeRestriction();
lastNameRestriction.BaseTypeName =
new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
XmlSchemaMaxLengthFacet maxLength = new XmlSchemaMaxLengthFacet();
maxLength.Value = "20";
lastNameRestriction.Facets.Add(maxLength);
lastNameType.Content = lastNameRestriction;
// Associate the elements and attributes with their types.
// Built-in type.
firstNameElement.SchemaTypeName =
new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
// User-defined type.
lastNameElement.SchemaTypeName =
new XmlQualifiedName("LastNameType", "http://www.tempuri.org");
// Built-in type.
idAttribute.SchemaTypeName = new XmlQualifiedName("positiveInteger",
"http://www.w3.org/2001/XMLSchema");
// Create the top-level Customer element.
XmlSchemaElement customerElement = new XmlSchemaElement();
customerElement.Name = "Customer";
// Create an anonymous complex type for the Customer element.
XmlSchemaComplexType customerType = new XmlSchemaComplexType();
XmlSchemaSequence sequence = new XmlSchemaSequence();
sequence.Items.Add(firstNameElement);
sequence.Items.Add(lastNameElement);
customerType.Particle = sequence;
// Add the CustomerId attribute to the complex type.
customerType.Attributes.Add(idAttribute);
// Set the SchemaType of the Customer element to
// the anonymous complex type created above.
customerElement.SchemaType = customerType;
' Create the simple type for the LastName element.
Dim lastNameType As XmlSchemaSimpleType = New XmlSchemaSimpleType()
lastNameType.Name = "LastNameType"
Dim lastNameRestriction As XmlSchemaSimpleTypeRestriction = _
New XmlSchemaSimpleTypeRestriction()
lastNameRestriction.BaseTypeName = _
New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
Dim maxLength As XmlSchemaMaxLengthFacet = New XmlSchemaMaxLengthFacet()
maxLength.Value = "20"
lastNameRestriction.Facets.Add(maxLength)
lastNameType.Content = lastNameRestriction
' Associate the elements and attributes with their types.
' Built-in type.
firstNameElement.SchemaTypeName = _
New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
' User-defined type.
lastNameElement.SchemaTypeName = _
New XmlQualifiedName("LastNameType", "http://www.tempuri.org")
' Built-in type.
idAttribute.SchemaTypeName = New XmlQualifiedName("positiveInteger", _
"http://www.w3.org/2001/XMLSchema")
' Create the top-level Customer element.
Dim customerElement As XmlSchemaElement = New XmlSchemaElement()
customerElement.Name = "Customer"
' Create an anonymous complex type for the Customer element.
Dim customerType As XmlSchemaComplexType = New XmlSchemaComplexType()
Dim sequence As XmlSchemaSequence = New XmlSchemaSequence()
sequence.Items.Add(firstNameElement)
sequence.Items.Add(lastNameElement)
customerType.Particle = sequence
' Add the CustomerId attribute to the complex type.
customerType.Attributes.Add(idAttribute)
' Set the SchemaType of the Customer element to
' the anonymous complex type created above.
customerElement.SchemaType = customerType
Criando e compilando esquemas
Neste ponto, os elementos e atributos filho, seus tipos correspondentes e o elemento de nível superior Customer
foram criados na memória usando a API do SOM. No exemplo de código a seguir, o elemento de esquema é criado usando a classe XmlSchema, os elementos e os tipos de nível superior são adicionados a ele usando a propriedade XmlSchema.Items e o esquema completo é compilado usando a classe XmlSchemaSet e criado no console.
// Create an empty schema.
XmlSchema^ customerSchema = gcnew XmlSchema();
customerSchema->TargetNamespace = "http://www.tempuri.org";
// Add all top-level element and types to the schema
customerSchema->Items->Add(customerElement);
customerSchema->Items->Add(lastNameType);
// Create an XmlSchemaSet to compile the customer schema.
XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet();
schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback);
schemaSet->Add(customerSchema);
schemaSet->Compile();
for each (XmlSchema^ schema in schemaSet->Schemas())
{
customerSchema = schema;
}
// Write the complete schema to the Console.
customerSchema->Write(Console::Out);
// Create an empty schema.
XmlSchema customerSchema = new XmlSchema();
customerSchema.TargetNamespace = "http://www.tempuri.org";
// Add all top-level element and types to the schema
customerSchema.Items.Add(customerElement);
customerSchema.Items.Add(lastNameType);
// Create an XmlSchemaSet to compile the customer schema.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
schemaSet.Add(customerSchema);
schemaSet.Compile();
foreach (XmlSchema schema in schemaSet.Schemas())
{
customerSchema = schema;
}
// Write the complete schema to the Console.
customerSchema.Write(Console.Out);
' Create an empty schema.
Dim customerSchema As XmlSchema = New XmlSchema()
customerSchema.TargetNamespace = "http://www.tempuri.org"
' Add all top-level element and types to the schema
customerSchema.Items.Add(customerElement)
customerSchema.Items.Add(lastNameType)
' Create an XmlSchemaSet to compile the customer schema.
Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
AddHandler schemaSet.ValidationEventHandler, AddressOf ValidationCallback
schemaSet.Add(customerSchema)
schemaSet.Compile()
For Each schema As XmlSchema In schemaSet.Schemas()
customerSchema = schema
Next
' Write the complete schema to the Console.
customerSchema.Write(Console.Out)
O método XmlSchemaSet.Compile valida o esquema cliente em relação às regras de um esquema XML e disponibiliza as propriedades de pós-compilação de esquema.
Observação
Todas as propriedades de pós-compilação de esquema na API do SOM diferem do conjunto de informações de pós-validação de esquema.
O objeto ValidationEventHandler adicionado à classe XmlSchemaSet é um delegado que chama o método de retorno de chamada ValidationCallback
para tratar avisos e erros de validação de esquema.
Veja a seguir o exemplo de código completo e o esquema cliente criado no console.
#using <System.Xml.dll>
using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;
ref class XmlSchemaCreateExample
{
public:
static void Main()
{
// Create the FirstName and LastName elements.
XmlSchemaElement^ firstNameElement = gcnew XmlSchemaElement();
firstNameElement->Name = "FirstName";
XmlSchemaElement^ lastNameElement = gcnew XmlSchemaElement();
lastNameElement->Name = "LastName";
// Create CustomerId attribute.
XmlSchemaAttribute^ idAttribute = gcnew XmlSchemaAttribute();
idAttribute->Name = "CustomerId";
idAttribute->Use = XmlSchemaUse::Required;
// Create the simple type for the LastName element.
XmlSchemaSimpleType^ lastNameType = gcnew XmlSchemaSimpleType();
lastNameType->Name = "LastNameType";
XmlSchemaSimpleTypeRestriction^ lastNameRestriction =
gcnew XmlSchemaSimpleTypeRestriction();
lastNameRestriction->BaseTypeName =
gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
XmlSchemaMaxLengthFacet^ maxLength = gcnew XmlSchemaMaxLengthFacet();
maxLength->Value = "20";
lastNameRestriction->Facets->Add(maxLength);
lastNameType->Content = lastNameRestriction;
// Associate the elements and attributes with their types.
// Built-in type.
firstNameElement->SchemaTypeName =
gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
// User-defined type.
lastNameElement->SchemaTypeName =
gcnew XmlQualifiedName("LastNameType", "http://www.tempuri.org");
// Built-in type.
idAttribute->SchemaTypeName = gcnew XmlQualifiedName("positiveInteger",
"http://www.w3.org/2001/XMLSchema");
// Create the top-level Customer element.
XmlSchemaElement^ customerElement = gcnew XmlSchemaElement();
customerElement->Name = "Customer";
// Create an anonymous complex type for the Customer element.
XmlSchemaComplexType^ customerType = gcnew XmlSchemaComplexType();
XmlSchemaSequence^ sequence = gcnew XmlSchemaSequence();
sequence->Items->Add(firstNameElement);
sequence->Items->Add(lastNameElement);
customerType->Particle = sequence;
// Add the CustomerId attribute to the complex type.
customerType->Attributes->Add(idAttribute);
// Set the SchemaType of the Customer element to
// the anonymous complex type created above.
customerElement->SchemaType = customerType;
// Create an empty schema.
XmlSchema^ customerSchema = gcnew XmlSchema();
customerSchema->TargetNamespace = "http://www.tempuri.org";
// Add all top-level element and types to the schema
customerSchema->Items->Add(customerElement);
customerSchema->Items->Add(lastNameType);
// Create an XmlSchemaSet to compile the customer schema.
XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet();
schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback);
schemaSet->Add(customerSchema);
schemaSet->Compile();
for each (XmlSchema^ schema in schemaSet->Schemas())
{
customerSchema = schema;
}
// Write the complete schema to the Console.
customerSchema->Write(Console::Out);
}
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()
{
XmlSchemaCreateExample::Main();
return 0;
}
using System;
using System.Xml;
using System.Xml.Schema;
class XmlSchemaCreateExample
{
static void Main(string[] args)
{
// Create the FirstName and LastName elements.
XmlSchemaElement firstNameElement = new XmlSchemaElement();
firstNameElement.Name = "FirstName";
XmlSchemaElement lastNameElement = new XmlSchemaElement();
lastNameElement.Name = "LastName";
// Create CustomerId attribute.
XmlSchemaAttribute idAttribute = new XmlSchemaAttribute();
idAttribute.Name = "CustomerId";
idAttribute.Use = XmlSchemaUse.Required;
// Create the simple type for the LastName element.
XmlSchemaSimpleType lastNameType = new XmlSchemaSimpleType();
lastNameType.Name = "LastNameType";
XmlSchemaSimpleTypeRestriction lastNameRestriction =
new XmlSchemaSimpleTypeRestriction();
lastNameRestriction.BaseTypeName =
new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
XmlSchemaMaxLengthFacet maxLength = new XmlSchemaMaxLengthFacet();
maxLength.Value = "20";
lastNameRestriction.Facets.Add(maxLength);
lastNameType.Content = lastNameRestriction;
// Associate the elements and attributes with their types.
// Built-in type.
firstNameElement.SchemaTypeName =
new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
// User-defined type.
lastNameElement.SchemaTypeName =
new XmlQualifiedName("LastNameType", "http://www.tempuri.org");
// Built-in type.
idAttribute.SchemaTypeName = new XmlQualifiedName("positiveInteger",
"http://www.w3.org/2001/XMLSchema");
// Create the top-level Customer element.
XmlSchemaElement customerElement = new XmlSchemaElement();
customerElement.Name = "Customer";
// Create an anonymous complex type for the Customer element.
XmlSchemaComplexType customerType = new XmlSchemaComplexType();
XmlSchemaSequence sequence = new XmlSchemaSequence();
sequence.Items.Add(firstNameElement);
sequence.Items.Add(lastNameElement);
customerType.Particle = sequence;
// Add the CustomerId attribute to the complex type.
customerType.Attributes.Add(idAttribute);
// Set the SchemaType of the Customer element to
// the anonymous complex type created above.
customerElement.SchemaType = customerType;
// Create an empty schema.
XmlSchema customerSchema = new XmlSchema();
customerSchema.TargetNamespace = "http://www.tempuri.org";
// Add all top-level element and types to the schema
customerSchema.Items.Add(customerElement);
customerSchema.Items.Add(lastNameType);
// Create an XmlSchemaSet to compile the customer schema.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
schemaSet.Add(customerSchema);
schemaSet.Compile();
foreach (XmlSchema schema in schemaSet.Schemas())
{
customerSchema = schema;
}
// Write the complete schema to the Console.
customerSchema.Write(Console.Out);
}
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.Xml
Imports System.Xml.Schema
Class XmlSchemaCreateExample
Shared Sub Main()
' Create the FirstName and LastName elements.
Dim firstNameElement As XmlSchemaElement = New XmlSchemaElement()
firstNameElement.Name = "FirstName"
Dim lastNameElement As XmlSchemaElement = New XmlSchemaElement()
lastNameElement.Name = "LastName"
' Create CustomerId attribute.
Dim idAttribute As XmlSchemaAttribute = New XmlSchemaAttribute()
idAttribute.Name = "CustomerId"
idAttribute.Use = XmlSchemaUse.Required
' Create the simple type for the LastName element.
Dim lastNameType As XmlSchemaSimpleType = New XmlSchemaSimpleType()
lastNameType.Name = "LastNameType"
Dim lastNameRestriction As XmlSchemaSimpleTypeRestriction = _
New XmlSchemaSimpleTypeRestriction()
lastNameRestriction.BaseTypeName = _
New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
Dim maxLength As XmlSchemaMaxLengthFacet = New XmlSchemaMaxLengthFacet()
maxLength.Value = "20"
lastNameRestriction.Facets.Add(maxLength)
lastNameType.Content = lastNameRestriction
' Associate the elements and attributes with their types.
' Built-in type.
firstNameElement.SchemaTypeName = _
New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
' User-defined type.
lastNameElement.SchemaTypeName = _
New XmlQualifiedName("LastNameType", "http://www.tempuri.org")
' Built-in type.
idAttribute.SchemaTypeName = New XmlQualifiedName("positiveInteger", _
"http://www.w3.org/2001/XMLSchema")
' Create the top-level Customer element.
Dim customerElement As XmlSchemaElement = New XmlSchemaElement()
customerElement.Name = "Customer"
' Create an anonymous complex type for the Customer element.
Dim customerType As XmlSchemaComplexType = New XmlSchemaComplexType()
Dim sequence As XmlSchemaSequence = New XmlSchemaSequence()
sequence.Items.Add(firstNameElement)
sequence.Items.Add(lastNameElement)
customerType.Particle = sequence
' Add the CustomerId attribute to the complex type.
customerType.Attributes.Add(idAttribute)
' Set the SchemaType of the Customer element to
' the anonymous complex type created above.
customerElement.SchemaType = customerType
' Create an empty schema.
Dim customerSchema As XmlSchema = New XmlSchema()
customerSchema.TargetNamespace = "http://www.tempuri.org"
' Add all top-level element and types to the schema
customerSchema.Items.Add(customerElement)
customerSchema.Items.Add(lastNameType)
' Create an XmlSchemaSet to compile the customer schema.
Dim schemaSet As XmlSchemaSet = New XmlSchemaSet()
AddHandler schemaSet.ValidationEventHandler, AddressOf ValidationCallback
schemaSet.Add(customerSchema)
schemaSet.Compile()
For Each schema As XmlSchema In schemaSet.Schemas()
customerSchema = schema
Next
' Write the complete schema to the Console.
customerSchema.Write(Console.Out)
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
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://www.tempuri.org" targetNamespace="http://www.tempuri.org" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Customer">
<xs:complexType>
<xs:sequence>
<xs:element name="FirstName" type="xs:string" />
<xs:element name="LastName" type="tns:LastNameType" />
</xs:sequence>
<xs:attribute name="CustomerId" type="xs:positiveInteger" use="required" />
</xs:complexType>
</xs:element>
<xs:simpleType name="LastNameType">
<xs:restriction base="xs:string">
<xs:maxLength value="20" />
</xs:restriction>
</xs:simpleType>
</xs:schema>