Leer en inglés

Compartir vía


XmlSchemaValidator Clase

Definición

Representa un motor de validación de esquema del lenguaje de definición de esquemas XML (XSD). La clase XmlSchemaValidator no se puede heredar.

C#
public sealed class XmlSchemaValidator
Herencia
XmlSchemaValidator

Ejemplos

En el ejemplo siguiente se valida el contosoBooks.xml archivo con el contosoBooks.xsd esquema . El ejemplo utiliza la clase XmlSerializer para deserializar el archivo contosoBooks.xml y pasar el valor de los nodos a los métodos de la clase XmlSchemaValidator.

C#
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Collections;

namespace Microsoft.Samples.Xml.Schema
{
    class XmlSchemaValidatorExamples
    {
        static void Main()
        {
            // The XML document to deserialize into the XmlSerializer object.
            XmlReader reader = XmlReader.Create("contosoBooks.xml");

            // The XmlSerializer object.
            XmlSerializer serializer = new XmlSerializer(typeof(ContosoBooks));
            ContosoBooks books = (ContosoBooks)serializer.Deserialize(reader);

            // The XmlSchemaSet object containing the schema used to validate the XML document.
            XmlSchemaSet schemaSet = new XmlSchemaSet();
            schemaSet.Add("http://www.contoso.com/books", "contosoBooks.xsd");

            // The XmlNamespaceManager object used to handle namespaces.
            XmlNamespaceManager manager = new XmlNamespaceManager(reader.NameTable);

            // Assign a ValidationEventHandler to handle schema validation warnings and errors.
            XmlSchemaValidator validator = new XmlSchemaValidator(reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None);
            validator.ValidationEventHandler += new ValidationEventHandler(SchemaValidationEventHandler);

            // Initialize the XmlSchemaValidator object.
            validator.Initialize();

            // Validate the bookstore element, verify that all required attributes are present
            // and prepare to validate child content.
            validator.ValidateElement("bookstore", "http://www.contoso.com/books", null);
            validator.GetUnspecifiedDefaultAttributes(new ArrayList());
            validator.ValidateEndOfAttributes(null);

            // Get the next exptected element in the bookstore context.
            XmlSchemaParticle[] particles = validator.GetExpectedParticles();
            XmlSchemaElement nextElement = particles[0] as XmlSchemaElement;
            Console.WriteLine("Expected Element: '{0}'", nextElement.Name);

            foreach (BookType book in books.Book)
            {
                // Validate the book element.
                validator.ValidateElement("book", "http://www.contoso.com/books", null);

                // Get the exptected attributes for the book element.
                Console.Write("\nExpected attributes: ");
                XmlSchemaAttribute[] attributes = validator.GetExpectedAttributes();
                foreach (XmlSchemaAttribute attribute in attributes)
                {
                    Console.Write("'{0}' ", attribute.Name);
                }
                Console.WriteLine();

                // Validate the genre attribute and display its post schema validation information.
                if (book.Genre != null)
                {
                    validator.ValidateAttribute("genre", "", book.Genre, schemaInfo);
                }
                DisplaySchemaInfo();

                // Validate the publicationdate attribute and display its post schema validation information.
                if (book.PublicationDate != null)
                {
                    validator.ValidateAttribute("publicationdate", "", dateTimeGetter(book.PublicationDate), schemaInfo);
                }
                DisplaySchemaInfo();

                // Validate the ISBN attribute and display its post schema validation information.
                if (book.Isbn != null)
                {
                    validator.ValidateAttribute("ISBN", "", book.Isbn, schemaInfo);
                }
                DisplaySchemaInfo();

                // After validating all the attributes for the current element with ValidateAttribute method,
                // you must call GetUnspecifiedDefaultAttributes to validate the default attributes.
                validator.GetUnspecifiedDefaultAttributes(new ArrayList());

                // Verify that all required attributes of the book element are present
                // and prepare to validate child content.
                validator.ValidateEndOfAttributes(null);

                // Validate the title element and its content.
                validator.ValidateElement("title", "http://www.contoso.com/books", null);
                validator.ValidateEndElement(null, book.Title);

                // Validate the author element, verify that all required attributes are present
                // and prepare to validate child content.
                validator.ValidateElement("author", "http://www.contoso.com/books", null);
                validator.GetUnspecifiedDefaultAttributes(new ArrayList());
                validator.ValidateEndOfAttributes(null);

                if (book.Author.Name != null)
                {
                    // Validate the name element and its content.
                    validator.ValidateElement("name", "http://www.contoso.com/books", null);
                    validator.ValidateEndElement(null, book.Author.Name);
                }

                if (book.Author.FirstName != null)
                {
                    // Validate the first-name element and its content.
                    validator.ValidateElement("first-name", "http://www.contoso.com/books", null);
                    validator.ValidateEndElement(null, book.Author.FirstName);
                }

                if (book.Author.LastName != null)
                {
                    // Validate the last-name element and its content.
                    validator.ValidateElement("last-name", "http://www.contoso.com/books", null);
                    validator.ValidateEndElement(null, book.Author.LastName);
                }

                // Validate the content of the author element.
                validator.ValidateEndElement(null);

                // Validate the price element and its content.
                validator.ValidateElement("price", "http://www.contoso.com/books", null);
                validator.ValidateEndElement(null, book.Price);

                // Validate the content of the book element.
                validator.ValidateEndElement(null);
            }

            // Validate the content of the bookstore element.
            validator.ValidateEndElement(null);

            // Close the XmlReader object.
            reader.Close();
        }

        static XmlSchemaInfo schemaInfo = new XmlSchemaInfo();
        static object dateTimeGetterContent;

        static object dateTimeGetterHandle()
        {
            return dateTimeGetterContent;
        }

        static XmlValueGetter dateTimeGetter(DateTime dateTime)
        {
            dateTimeGetterContent = dateTime;
            return new XmlValueGetter(dateTimeGetterHandle);
        }

        static void DisplaySchemaInfo()
        {
            if (schemaInfo.SchemaElement != null)
            {
                Console.WriteLine("Element '{0}' with type '{1}' is '{2}'",
                    schemaInfo.SchemaElement.Name, schemaInfo.SchemaType, schemaInfo.Validity);
            }
            else if (schemaInfo.SchemaAttribute != null)
            {
                Console.WriteLine("Attribute '{0}' with type '{1}' is '{2}'",
                    schemaInfo.SchemaAttribute.Name, schemaInfo.SchemaType, schemaInfo.Validity);
            }
        }

        static void SchemaValidationEventHandler(object sender, ValidationEventArgs e)
        {
            switch (e.Severity)
            {
                case XmlSeverityType.Error:
                    Console.WriteLine("\nError: {0}", e.Message);
                    break;
                case XmlSeverityType.Warning:
                    Console.WriteLine("\nWarning: {0}", e.Message);
                    break;
            }
        }
    }

    [XmlRootAttribute("bookstore", Namespace = "http://www.contoso.com/books", IsNullable = false)]
    public class ContosoBooks
    {
        [XmlElementAttribute("book")]
        public BookType[] Book;
    }

    public class BookType
    {
        [XmlAttributeAttribute("genre")]
        public string Genre;

        [XmlAttributeAttribute("publicationdate", DataType = "date")]
        public DateTime PublicationDate;

        [XmlAttributeAttribute("ISBN")]
        public string Isbn;

        [XmlElementAttribute("title")]
        public string Title;

        [XmlElementAttribute("author")]
        public BookAuthor Author;

        [XmlElementAttribute("price")]
        public Decimal Price;
    }

    public class BookAuthor
    {
        [XmlElementAttribute("name")]
        public string Name;

        [XmlElementAttribute("first-name")]
        public string FirstName;

        [XmlElementAttribute("last-name")]
        public string LastName;
    }
}

En el ejemplo se toma como entrada el archivo contosoBooks.xml.

XML
<?xml version="1.0" encoding="utf-8" ?>
<bookstore xmlns="http://www.contoso.com/books">
    <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
        <author>
            <first-name>Benjamin</first-name>
            <last-name>Franklin</last-name>
        </author>
        <price>8.99</price>
    </book>
    <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
        <author>
            <first-name>Herman</first-name>
            <last-name>Melville</last-name>
        </author>
        <price>11.99</price>
    </book>
    <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <name>Plato</name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

En el ejemplo también se toma como entrada el archivo contosoBooks.xsd.

XML
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.contoso.com/books" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="bookstore">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="unbounded" name="book">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="title" type="xs:string" />
                            <xs:element name="author">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element minOccurs="0" name="name" type="xs:string" />
                                        <xs:element minOccurs="0" name="first-name" type="xs:string" />
                                        <xs:element minOccurs="0" name="last-name" type="xs:string" />
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                            <xs:element name="price" type="xs:decimal" />
                        </xs:sequence>
                        <xs:attribute name="genre" type="xs:string" use="required" />
                        <xs:attribute name="publicationdate" type="xs:date" use="required" />
                        <xs:attribute name="ISBN" type="xs:string" use="required" />
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Comentarios

Importante

  • No use esquemas de orígenes o ubicaciones desconocidos o que no sean de confianza. Si lo hace, se pondrá en peligro la seguridad del código.
  • Los esquemas XML (incluidos los esquemas insertados) son intrínsecamente vulnerables a ataques de denegación de servicio; no los acepte en escenarios que no son de confianza.
  • Los mensajes de error y las excepciones de validación de esquemas pueden exponer información confidencial sobre el modelo de contenido o las rutas de acceso de URI al archivo de esquema. Tenga cuidado de no exponer esta información a los autores de llamadas que no son de confianza.

La clase XmlSchemaValidator incluye un mecanismo eficiente y de alto rendimiento para validar datos XML con esquemas XML mediante inserción. Por ejemplo, la clase XmlSchemaValidator le permite validar un conjunto de información XML en el lugar sin tener que serializarla como un documento XML y, a continuación, volver a analizar el documento utilizando un sistema de lectura XML de validación. La XmlSchemaValidator clase también se puede usar para crear motores de validación a través de orígenes de datos XML personalizados o como una manera de crear un escritor XML de validación.

Para obtener más información sobre la XmlSchemaValidator clase , vea el tema XmlSchemaValidator Push-Based Validation .

Importante

Las ProcessInlineSchema marcas de validación y ProcessSchemaLocation de un XmlSchemaValidator objeto no se establecen de forma predeterminada. Además, la XmlResolver propiedad de un XmlSchemaValidator objeto es null de forma predeterminada. Como resultado, los esquemas externos a los que se hace referencia en incluyen, importan o vuelven a definir elementos no se resuelven de forma predeterminada.

Constructores

Propiedades

LineInfoProvider

Obtiene o establece la información del número de línea del nodo XML que se está validando.

SourceUri

Obtiene o establece el URI de origen del nodo XML que se está validando.

ValidationEventSender

Obtiene o establece el objeto enviado como objeto de remitente de un evento de validación.

XmlResolver

Establece el XmlResolver objeto utilizado para resolver xs:import los elementos y xs:include , así como xsi:schemaLocation los atributos y xsi:noNamespaceSchemaLocation .

Métodos

AddSchema(XmlSchema)

Agrega un esquema del lenguaje de definición de esquemas XML (XSD) al conjunto de esquemas usado para la validación.

EndValidation()

Finaliza la validación y comprueba las restricciones de identidad de todo el documento XML.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetExpectedAttributes()

Devuelve los atributos esperados para el contexto del elemento actual.

GetExpectedParticles()

Devuelve las partículas esperadas en el contexto del elemento actual.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
GetUnspecifiedDefaultAttributes(ArrayList)

Valida restricciones de identidad en los atributos predeterminados y rellena la lista ArrayList especificada con objetos XmlSchemaAttribute de todos los atributos con valores predeterminados que no se hayan validado previamente usando el método ValidateAttribute en el contexto del elemento.

Initialize()

Inicializa el estado del objeto XmlSchemaValidator.

Initialize(XmlSchemaObject)

Inicializa el estado del objeto XmlSchemaValidator utilizando el objeto XmlSchemaObject especificado para la validación parcial.

MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
SkipToEndElement(XmlSchemaInfo)

Omite la validación del contenido del elemento actual y prepara el objeto XmlSchemaValidator para validar contenido en el contexto del elemento primario.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
ValidateAttribute(String, String, String, XmlSchemaInfo)

Valida el nombre del atributo, el URI del espacio de nombres y el valor en el contexto del elemento actual.

ValidateAttribute(String, String, XmlValueGetter, XmlSchemaInfo)

Valida el nombre del atributo, el URI del espacio de nombres y el valor en el contexto del elemento actual.

ValidateElement(String, String, XmlSchemaInfo)

Valida el elemento en el contexto actual.

ValidateElement(String, String, XmlSchemaInfo, String, String, String, String)

Valida el elemento en el contexto actual con los valores de xsi:Typeatributo , xsi:Nil, xsi:SchemaLocationy xsi:NoNamespaceSchemaLocation especificados.

ValidateEndElement(XmlSchemaInfo)

Comprueba si el contenido de texto del elemento es válido según su tipo de datos para los elementos con contenido simple y si el contenido del elemento actual está completo para los elementos con contenido complejo.

ValidateEndElement(XmlSchemaInfo, Object)

Comprueba si el contenido del texto del elemento especificado es válido según su tipo de datos.

ValidateEndOfAttributes(XmlSchemaInfo)

Comprueba si todos los atributos requeridos del contexto del elemento están presentes y prepara el objeto XmlSchemaValidator para validar el contenido secundario del elemento.

ValidateText(String)

Valida si la cadena string de texto especificada se permite en el contexto del elemento actual y acumula el texto para la validación si el contenido del elemento actual es simple.

ValidateText(XmlValueGetter)

Valida si el texto que devuelve el objeto XmlValueGetter especificado se permite en el contexto del elemento actual y acumula el texto para la validación si el contenido del elemento actual es simple.

ValidateWhitespace(String)

Valida si se permite el espacio en blanco de la cadena string especificada en el contexto del elemento actual y acumula el espacio en blanco para la validación si el contenido del elemento actual es simple.

ValidateWhitespace(XmlValueGetter)

Valida si se permite el espacio en blanco que devuelve el objeto XmlValueGetter especificado en el contexto del elemento actual y acumula el espacio en blanco para la validación si el contenido del elemento actual es simple.

Eventos

ValidationEventHandler

ValidationEventHandler que recibe advertencias y errores detectados durante la validación del esquema.

Se aplica a

Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Consulte también