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.
Un esquema XML puede contener <xs:import />
elementos , <xs:include />
y <xs:redefine />
. Estos elementos de esquema hacen referencia a otros esquemas XML que se pueden usar para complementar la estructura del esquema que incluye o importa. Las XmlSchemaImport, XmlSchemaInclude y XmlSchemaRedefine clases corresponden a estos elementos en la API del Modelo de Objetos de Esquema (SOM).
Incluir o importar un esquema XML
En el ejemplo de código siguiente se complementa el esquema de cliente creado en el tema Building XML Schemas (Compilar esquemas XML ) con el esquema de direcciones. Complementar el esquema del cliente con el esquema de direcciones hace que los tipos de dirección estén disponibles en el esquema del cliente.
El esquema de direcciones se puede incorporar mediante los elementos <xs:include />
o <xs:import />
para utilizar los componentes del esquema de direcciones as-is, o mediante el elemento <xs:redefine />
para modificar cualquiera de sus componentes y adaptarlo a las necesidades del esquema del cliente. Dado que el esquema de direcciones tiene un targetNamespace
que es diferente del del esquema del cliente, se usa el <xs:import />
elemento y, por tanto, se usa la semántica de importación.
El ejemplo de código incluye el esquema de direcciones en los pasos siguientes.
Agrega el esquema del cliente y el esquema de direcciones a un nuevo XmlSchemaSet objeto y, a continuación, los compila. El delegado ValidationEventHandler controla las advertencias y errores de validación de esquemas detectados al leer o compilar los esquemas.
Extrae los objetos compilados XmlSchema de los esquemas 'cliente' y 'dirección' de XmlSchemaSet al iterar sobre la propiedad Schemas. Dado que los esquemas se compilan, se puede acceder a las propiedades post-Schema-Compilation-Infoset (PSCI).
Crea un XmlSchemaImport objeto , establece la Namespace propiedad de la importación en el espacio de nombres del esquema de direcciones, establece la Schema propiedad de la importación en el XmlSchema objeto del esquema de direcciones y agrega la importación a la Includes propiedad del esquema del cliente.
Reprocesa y compila el objeto modificado XmlSchema del esquema del cliente utilizando los métodos Reprocess y Compile de la clase XmlSchemaSet y lo escribe en la consola.
Por último, escribe recursivamente todos los esquemas importados en el esquema del cliente en la consola mediante la Includes propiedad del esquema del cliente. La Includes propiedad proporciona acceso a todos los elementos de inclusión, importación o redefinición agregados a un esquema.
A continuación se muestra el ejemplo de código completo y los esquemas de cliente y dirección escritos en la consola.
using System;
using System.Xml;
using System.Xml.Schema;
class XmlSchemaImportExample
{
static void Main(string[] args)
{
// Add the customer and address schemas to a new XmlSchemaSet and compile them.
// Any schema validation warnings and errors encountered reading or
// compiling the schemas are handled by the ValidationEventHandler delegate.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
schemaSet.Add("http://www.tempuri.org", "customer.xsd");
schemaSet.Add("http://www.example.com/IPO", "address.xsd");
schemaSet.Compile();
// Retrieve the compiled XmlSchema objects for the customer and
// address schema from the XmlSchemaSet by iterating over
// the Schemas property.
XmlSchema customerSchema = null;
XmlSchema addressSchema = null;
foreach (XmlSchema schema in schemaSet.Schemas())
{
if (schema.TargetNamespace == "http://www.tempuri.org")
customerSchema = schema;
else if (schema.TargetNamespace == "http://www.example.com/IPO")
addressSchema = schema;
}
// Create an XmlSchemaImport object, set the Namespace property
// to the namespace of the address schema, the Schema property
// to the address schema, and add it to the Includes property
// of the customer schema.
XmlSchemaImport import = new XmlSchemaImport();
import.Namespace = "http://www.example.com/IPO";
import.Schema = addressSchema;
customerSchema.Includes.Add(import);
// Reprocess and compile the modified XmlSchema object
// of the customer schema and write it to the console.
schemaSet.Reprocess(customerSchema);
schemaSet.Compile();
customerSchema.Write(Console.Out);
// Recursively write all of the schemas imported into the
// customer schema to the console using the Includes
// property of the customer schema.
RecurseExternals(customerSchema);
}
static void RecurseExternals(XmlSchema schema)
{
foreach (XmlSchemaExternal external in schema.Includes)
{
if (external.SchemaLocation != null)
{
Console.WriteLine($"External SchemaLocation: {external.SchemaLocation}");
}
if (external is XmlSchemaImport)
{
XmlSchemaImport import = external as XmlSchemaImport;
Console.WriteLine($"Imported namespace: {import.Namespace}");
}
if (external.Schema != null)
{
external.Schema.Write(Console.Out);
RecurseExternals(external.Schema);
}
}
}
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 XmlSchemaImportExample
Shared Sub Main()
' Add the customer and address schemas to a new XmlSchemaSet and compile them.
' Any schema validation warnings and errors encountered reading or
' compiling the schemas 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.Add("http://www.example.com/IPO", "address.xsd")
schemaSet.Compile()
' Retrieve the compiled XmlSchema objects for the customer and
' address schema from the XmlSchemaSet by iterating over
' the Schemas property.
Dim customerSchema As XmlSchema = Nothing
Dim addressSchema As XmlSchema = Nothing
For Each schema As XmlSchema In schemaSet.Schemas()
If schema.TargetNamespace = "http://www.tempuri.org" Then
customerSchema = schema
ElseIf schema.TargetNamespace = "http://www.example.com/IPO" Then
addressSchema = schema
End If
Next
' Create an XmlSchemaImport object, set the Namespace property
' to the namespace of the address schema, the Schema property
' to the address schema, and add it to the Includes property
' of the customer schema.
Dim import As XmlSchemaImport = New XmlSchemaImport()
import.Namespace = "http://www.example.com/IPO"
import.Schema = addressSchema
customerSchema.Includes.Add(import)
' Reprocess and compile the modified XmlSchema object
' of the customer schema and write it to the console.
schemaSet.Reprocess(customerSchema)
schemaSet.Compile()
customerSchema.Write(Console.Out)
' Recursively write all of the schemas imported into the
' customer schema to the console using the Includes
' property of the customer schema.
RecurseExternals(customerSchema)
End Sub
Shared Sub RecurseExternals(ByVal schema As XmlSchema)
For Each external As XmlSchemaExternal In Schema.Includes
If Not external.SchemaLocation = Nothing Then
Console.WriteLine("External SchemaLocation: {0}", external.SchemaLocation)
End If
If external.GetType() Is GetType(XmlSchemaImport) Then
Dim import As XmlSchemaImport = CType(external, XmlSchemaImport)
Console.WriteLine("Imported namespace: {0}", import.Namespace)
End If
If Not external.Schema Is Nothing Then
external.Schema.Write(Console.Out)
RecurseExternals(external.Schema)
End If
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
<?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:import namespace="http://www.example.com/IPO" />
<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>
<schema targetNamespace="http://www.example.com/IPO" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ipo="http://www.example.com/IPO">
<annotation>
<documentation xml:lang="en">
Addresses for International Purchase order schema
Copyright 2000 Example.com. All rights reserved.
</documentation>
</annotation>
<complexType name="Address">
<sequence>
<element name="name" type="string"/>
<element name="street" type="string"/>
<element name="city" type="string"/>
</sequence>
</complexType>
<complexType name="USAddress">
<complexContent>
<extension base="ipo:Address">
<sequence>
<element name="state" type="ipo:USState"/>
<element name="zip" type="positiveInteger"/>
</sequence>
</extension>
</complexContent>
</complexType>
<!-- other Address derivations for more countries or regions -->
<simpleType name="USState">
<restriction base="string">
<enumeration value="AK"/>
<enumeration value="AL"/>
<enumeration value="AR"/>
<!-- and so on ... -->
</restriction>
</simpleType>
</schema>
Para obtener más información sobre los elementos <xs:import />
, <xs:include />
y <xs:redefine />
, y las clases XmlSchemaImport, XmlSchemaInclude y XmlSchemaRedefine, vea el esquema W3C XML y la documentación de referencia de la clase del espacio de nombres System.Xml.Schema.