Compilazione di XML Schema
Le classi nello spazio dei nomi System.Xml.Schema sono associate alle strutture definite nella raccomandazione W3C (World Wide Web Consortium) XML Schema e possono essere usate per compilare schemi XML in memoria.
Compilazione di un XML Schema
Nei seguenti esempi di codice, per compilare in memoria uno schema XML del cliente viene usata l'API del modello SOM (Schema Object Model).
Creazione di elementi e attributi
Negli esempi di codice, lo schema del cliente viene compilato dal basso verso l'alto, ovvero vengono creati prima gli elementi e gli attributi figlio con i tipi corrispondenti, poi gli elementi principali.
Nel seguente esempio di codice gli elementi FirstName
, LastName
e l'attributo CustomerId
dello schema del cliente vengono creati usando le classi XmlSchemaElement e XmlSchemaAttribute del modello SOM. A parte le proprietà Name delle classi XmlSchemaElement e XmlSchemaAttribute, che corrispondono all'attributo "name" degli elementi <xs:element />
e <xs:attribute />
in XML Schema, tutti gli altri attributi consentiti dallo schema (defaultValue
, fixedValue
, form
e così via) contengono le proprietà corrispondenti nelle classi 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
Creazione di tipi di schema
Il contenuto degli elementi e degli attributi è definito dai relativi tipi. Per creare elementi e attributi i cui tipi corrispondano a uno dei tipi incorporati nello schema, la proprietà SchemaTypeName della classe XmlSchemaElement o XmlSchemaAttribute viene impostata con il nome completo corrispondente del tipo incorporato usando la classe XmlQualifiedName. Per creare un tipo definito dall'utente per gli elementi e gli attributi, viene creato un nuovo tipo semplice o complesso usando la classe XmlSchemaSimpleType o XmlSchemaComplexType.
Nota
Per creare tipi semplici o complessi senza nome anonimo figlio di un elemento o attributo (si applicano solo tipi semplici per gli attributi), impostare il SchemaType proprietà del XmlSchemaElement o XmlSchemaAttribute alle classi di tipo semplice o complesso senza nome, anziché il SchemaTypeName proprietà del XmlSchemaElement o XmlSchemaAttribute classi.
Gli schemi XML consentono di derivare per restrizione da altri tipi semplici (incorporati o definiti dall'utente) sia i tipi semplici anonimi sia i tipi semplici denominati oppure di crearli come un elenco o un'unione di altri tipi semplici. La classe XmlSchemaSimpleTypeRestriction consente di creare un tipo semplice per restrizione dal tipo xs:string
incorporato. Per creare tipi di unione o di elenco, è possibile usare anche la classe XmlSchemaSimpleTypeList o XmlSchemaSimpleTypeUnion. La proprietà XmlSchemaSimpleType.Content indica se è una restrizione, un elenco o un'unione di tipi semplici.
Nel seguente esempio di codice il tipo dell'elemento FirstName
è un tipo xs:string
incorporato, il tipo dell'elemento LastName
è un tipo semplice denominato che è una restrizione del tipo xs:string
incorporato, il valore del facet MaxLength
è 20 e il tipo dell'attributo CustomerId
è il tipo xs:positiveInteger
incorporato. L'elemento Customer
è un tipo complesso anonimo la cui particella è rappresentata dalla sequenza degli elementi FirstName
e LastName
e i cui attributi contengono l'attributo CustomerId
.
Nota
È inoltre possibile usare le classi XmlSchemaChoice o XmlSchemaAll come particella del tipo complesso per replicare la semantica <xs:choice />
o <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
Creazione e compilazione di schemi
A questo punto, usando l'API del modello SOM, sono stati creati in memoria gli elementi e attributi figlio, i tipi corrispondenti e l'elemento di livello principale Customer
. Nel seguente esempio di codice l'elemento dello schema viene creato usando la classe XmlSchema, vi vengono aggiunti i tipi e gli elementi di livello principale tramite la proprietà XmlSchema.Items, quindi lo schema completo viene compilato usando la classe XmlSchemaSet e viene scritto nella 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)
Il metodo XmlSchemaSet.Compile convalida lo schema del cliente in base alle regole per gli schemi XML e rende disponibili le proprietà successive alla compilazione dello schema.
Nota
Tutte le proprietà nell'API del modello SOM successive alla compilazione dello schema sono diverse dall'infoset sulla convalida post-schema.
Il tipo ValidationEventHandler aggiunto al tipo XmlSchemaSet è un delegato che chiama il metodo di callback ValidationCallback
per gestire gli avvisi e gli errori di convalida dello schema.
Di seguito è riportato l'esempio di codice completo e lo schema del cliente scritto nella 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>