Criando esquemas XML
As classes no System.Xml.Schema namespace mapeiam para as estruturas definidas na Recomendação de Esquema XML do World Wide Web Consortium (W3C) e podem ser usadas para criar esquemas XML na memória.
Criando um esquema XML
Nos exemplos de código a seguir, a API SOM é usada para criar um esquema XML do cliente na memória.
Criando elementos e atributos
Os exemplos de código criam o esquema do cliente de baixo para cima, criando os elementos filho, atributos e seus tipos correspondentes primeiro e, em seguida, os elementos de nível superior.
No exemplo de código a seguir, os FirstName
elementos CustomerId
e LastName
e o atributo do esquema do cliente são criados usando as XmlSchemaElement classes e XmlSchemaAttribute do SOM. Além das propriedades das XmlSchemaElement classes andXmlSchemaAttribute, que correspondem ao atributo "name" dos <xs:element />
elementos 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 XmlSchemaElement classes e XmlSchemaAttribute .Name
// 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 dos elementos e atributos é definido pelos seus tipos. Para criar elementos e atributos cujos tipos são um dos tipos de esquema internos, a SchemaTypeNameXmlSchemaElement propriedade das classes ou XmlSchemaAttribute é definida com o nome qualificado correspondente do tipo interno usando a XmlQualifiedName classe. Para criar um tipo definido pelo usuário para elementos e atributos, um novo tipo simples ou complexo é criado usando a XmlSchemaSimpleType classe or XmlSchemaComplexType .
Nota
Para criar tipos simples ou complexos sem nome que são filhos anônimos de um elemento ou atributo (somente tipos simples se aplicam a atributos), defina a SchemaType propriedade das classes ou XmlSchemaAttribute para o XmlSchemaElement tipo simples ou complexo sem nome, em vez da SchemaTypeName propriedade das XmlSchemaElement classes ouXmlSchemaAttribute.
Os esquemas XML permitem que tipos simples anônimos e nomeados sejam derivados por 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 XmlSchemaSimpleTypeRestriction classe é usada para criar um tipo simples, restringindo o tipo interno xs:string
. Você também pode usar as XmlSchemaSimpleTypeList classes ou XmlSchemaSimpleTypeUnion para criar tipos de lista ou união. A XmlSchemaSimpleType.Content propriedade indica se é uma simples restrição de tipo, lista ou união.
No exemplo de código a seguir, o FirstName
tipo do elemento é o tipo xs:string
interno, o LastName
tipo do elemento é um tipo simples nomeado que é uma restrição do tipo xs:string
interno, com um MaxLength
valor de faceta de 20, e o CustomerId
tipo do atributo é o tipo xs:positiveInteger
interno. O Customer
elemento é um tipo complexo anônimo cuja partícula é a sequência dos FirstName
elementos e LastName
cujos atributos contêm o CustomerId
atributo.
Nota
Você também pode usar as XmlSchemaChoice classes ou XmlSchemaAll como a partícula do tipo complexo para replicar <xs:choice />
ou <xs:all />
semântica.
// 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 Customer
superior foram criados na memória usando a API SOM. No exemplo de código a seguir, o elemento schema é criado usando a XmlSchema classe, os elementos e tipos de nível superior são adicionados a ele usando a XmlSchema.Items propriedade e o esquema completo é compilado usando a XmlSchemaSet classe e gravado 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 XmlSchemaSet.Compile método valida o esquema do cliente em relação às regras de um esquema XML e disponibiliza propriedades de compilação pós-esquema.
Nota
Todas as propriedades de compilação pós-esquema na API SOM diferem do Post-Schema-Validation-Infoset.
O ValidationEventHandler adicionado ao XmlSchemaSet é um delegado que chama o método ValidationCallback
de retorno de chamada para manipular avisos e erros de validação de esquema.
A seguir está o exemplo de código completo e o esquema do cliente gravado 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>