Validación de un documento XML en el DOMValidating an XML Document in the DOM

La clase XmlDocument no valida el código XML en el Modelo de objetos de documento (DOM) con un esquema del lenguaje de definición de esquemas XML (XSD) ni una definición de tipo de documento (DTD) de manera predeterminada; solo se comprueba si el código XML es correcto.TheXmlDocument class does not validate the XML in the Document Object Model (DOM) against an XML Schema definition language (XSD) schema or document type definition (DTD) by default; the XML is only verified to be well-formed.

Para validar el código XML en el DOM, puede validarlo a medida que se carga en el DOM pasando un XmlReader de validación de esquemas al método Load de la clase XmlDocument, o bien validar en el DOM un documento XML que no estuviera validado previamente utilizando el método Validate de la clase XmlDocument.To validate the XML in the DOM, you can validate the XML as it is loaded into the DOM by passing a schema-validating XmlReader to the Load method of the XmlDocument class, or validate a previously unvalidated XML document in the DOM using the Validate method of the XmlDocument class.

Validación de un documento XML a medida que se carga en el DOMValidating an XML Document As It Is Loaded into the DOM

La clase XmlDocument valida los datos XML a medida que se cargan en el DOM cuando se pasa un XmlReader de validación al método Load de la clase XmlDocument.The XmlDocument class validates the XML data as it is loaded into the DOM when a validating XmlReader is passed to the Load method of the XmlDocument class.

Después de realizar la validación correctamente, se aplican los valores predeterminados del esquema, los valores de texto se convierten en valores atómicos como sea preciso y la información de tipos se asocia a los elementos de información validados.After successful validation, schema defaults are applied, text values are converted to atomic values as necessary, and type information is associated with validated information items. Como resultado, los datos XML con tipo reemplazan a los datos XML sin tipo anteriores.As a result, typed XML data replaces previously untyped XML data.

Creación de un XmlReader de validación de esquemas XMLCreating an XML Schema-Validating XmlReader

Para crear un XmlReader de validación de esquemas XML, siga estos pasos.To create an XML schema-validating XmlReader, follow these steps.

  1. Cree una nueva instancia de XmlReaderSettings.Construct a new XmlReaderSettings instance.

  2. Agregue un esquema XML a la propiedad Schemas de la instancia XmlReaderSettings.Add an XML schema to the Schemas property of the XmlReaderSettings instance.

  3. Especifique Schema como ValidationType.Specify Schema as the ValidationType.

  4. Opcionalmente, especifique ValidationFlags y ValidationEventHandler para que controlen las advertencias y errores de validación de esquemas que se encuentren durante la validación.Optionally specify ValidationFlags and a ValidationEventHandler to handle schema validation errors and warnings encountered during validation.

  5. Por último, pase el objeto XmlReaderSettings al método Create de la clase XmlReader junto con el documento XML, para crear un XmlReader de validación de esquemas.Finally, pass the XmlReaderSettings object to the Create method of the XmlReader class along with the XML document, creating a schema-validating XmlReader.

EjemploExample

En el siguiente código de ejemplo, un XmlReader de validación de esquemas valida los datos XML cargados en el DOM.In the code example that follows, a schema-validating XmlReader validates the XML data loaded into the DOM. Se realizan modificaciones no válidas en el documento XML y, a continuación, dicho documento se vuelve a validar, lo que produce errores de validación del esquema.Invalid modifications are made to the XML document and the document is then revalidated, causing schema validation errors. Por último, se corrige uno de los errores y, a continuación, se valida parcialmente parte del documento XML.Finally, one of the errors is corrected, and then part of the XML document is partially validated.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;

ref class XmlDocumentValidationExample
{
public:

    static void Main()
    {
        try
        {
            // Create a schema validating XmlReader.
            XmlReaderSettings^ settings = gcnew XmlReaderSettings();
            settings->Schemas->Add("http://www.contoso.com/books", "contosoBooks.xsd");
            ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(ValidationEventHandlerOne);
            settings->ValidationEventHandler += eventHandler;
            settings->ValidationFlags = settings->ValidationFlags | XmlSchemaValidationFlags::ReportValidationWarnings;
            settings->ValidationType = ValidationType::Schema;

            XmlReader^ reader = XmlReader::Create("contosoBooks.xml", settings);

            // The XmlDocument validates the XML document contained
            // in the XmlReader as it is loaded into the DOM.
            XmlDocument^ document = gcnew XmlDocument();
            document->Load(reader);

            // Make an invalid change to the first and last 
            // price elements in the XML document, and write
            // the XmlSchemaInfo values assigned to the price
            // element during load validation to the console.
            XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(document->NameTable);
            manager->AddNamespace("bk", "http://www.contoso.com/books");

            XmlNode^ priceNode = document->SelectSingleNode("/bk:bookstore/bk:book/bk:price", manager);

            Console::WriteLine("SchemaInfo.IsDefault: {0}", priceNode->SchemaInfo->IsDefault);
            Console::WriteLine("SchemaInfo.IsNil: {0}", priceNode->SchemaInfo->IsNil);
            Console::WriteLine("SchemaInfo.SchemaElement: {0}", priceNode->SchemaInfo->SchemaElement);
            Console::WriteLine("SchemaInfo.SchemaType: {0}", priceNode->SchemaInfo->SchemaType);
            Console::WriteLine("SchemaInfo.Validity: {0}", priceNode->SchemaInfo->Validity);

            priceNode->InnerXml = "A";

            XmlNodeList^ priceNodes = document->SelectNodes("/bk:bookstore/bk:book/bk:price", manager);
            XmlNode^ lastprice = priceNodes[priceNodes->Count - 1];
            
            lastprice->InnerXml = "B";

            // Validate the XML document with the invalid changes.
            // The invalid changes cause schema validation errors.
            document->Validate(eventHandler);

            // Correct the invalid change to the first price element.
            priceNode->InnerXml = "8.99";

            // Validate only the first book element. The last book
            // element is invalid, but not included in validation.
            XmlNode^ bookNode = document->SelectSingleNode("/bk:bookstore/bk:book", manager);
            document->Validate(eventHandler, bookNode);
        }
        catch (XmlException^ ex)
        {
            Console::WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex->Message);
        }
        catch(XmlSchemaValidationException^ ex)
        {
            Console::WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex->Message);
        }
        catch (Exception^ ex)
        {
            Console::WriteLine("XmlDocumentValidationExample.Exception: {0}", ex->Message);
        }
    }

    static void ValidationEventHandlerOne(Object^ sender, ValidationEventArgs^ args)
    {
        if (args->Severity == XmlSeverityType::Warning)
            Console::Write("\nWARNING: ");
        else if (args->Severity == XmlSeverityType::Error)
            Console::Write("\nERROR: ");

        Console::WriteLine(args->Message);
    }
};

int main()
{
    XmlDocumentValidationExample::Main();
    return 0;
}
using System;
using System.Xml;
using System.Xml.Schema;

class XmlDocumentValidationExample
{
    static void Main(string[] args)
    {
        try
        {
            // Create a schema validating XmlReader.
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler);
            settings.ValidationFlags = settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationType = ValidationType.Schema;

            XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);

            // The XmlDocument validates the XML document contained
            // in the XmlReader as it is loaded into the DOM.
            XmlDocument document = new XmlDocument();
            document.Load(reader);

            // Make an invalid change to the first and last 
            // price elements in the XML document, and write
            // the XmlSchemaInfo values assigned to the price
            // element during load validation to the console.
            XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
            manager.AddNamespace("bk", "http://www.contoso.com/books");

            XmlNode priceNode = document.SelectSingleNode(@"/bk:bookstore/bk:book/bk:price", manager);

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault);
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil);
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement);
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType);
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity);

            priceNode.InnerXml = "A";

            XmlNodeList priceNodes = document.SelectNodes(@"/bk:bookstore/bk:book/bk:price", manager);
            XmlNode lastprice = priceNodes[priceNodes.Count - 1];
            
            lastprice.InnerXml = "B";

            // Validate the XML document with the invalid changes.
            // The invalid changes cause schema validation errors.
            document.Validate(ValidationEventHandler);

            // Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99";

            // Validate only the first book element. The last book
            // element is invalid, but not included in validation.
            XmlNode bookNode = document.SelectSingleNode(@"/bk:bookstore/bk:book", manager);
            document.Validate(ValidationEventHandler, bookNode);
        }
        catch (XmlException ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message);
        }
        catch(XmlSchemaValidationException ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message);
        }
    }

    static void ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("\nWARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("\nERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlDocumentValidationExample

    Shared Sub Main()

        Try

            ' Create a schema validating XmlReader.
            Dim settings As XmlReaderSettings = New XmlReaderSettings()
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")
            AddHandler settings.ValidationEventHandler, New ValidationEventHandler(AddressOf ValidationEventHandler)
            settings.ValidationFlags = settings.ValidationFlags And XmlSchemaValidationFlags.ReportValidationWarnings
            settings.ValidationType = ValidationType.Schema

            Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings)

            ' The XmlDocument validates the XML document contained
            ' in the XmlReader as it is loaded into the DOM.
            Dim document As XmlDocument = New XmlDocument()
            document.Load(reader)

            ' Make an invalid change to the first and last 
            ' price elements in the XML document, and write
            ' the XmlSchemaInfo values assigned to the price
            ' element during load validation to the console.
            Dim manager As XmlNamespaceManager = New XmlNamespaceManager(document.NameTable)
            manager.AddNamespace("bk", "http://www.contoso.com/books")

            Dim priceNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book/bk:price", manager)

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault)
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil)
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement)
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType)
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity)

            priceNode.InnerXml = "A"

            Dim priceNodes As XmlNodeList = document.SelectNodes("/bk:bookstore/bk:book/bk:price", manager)
            Dim lastprice As XmlNode = priceNodes(priceNodes.Count - 1)

            lastprice.InnerXml = "B"

            ' Validate the XML document with the invalid changes.
            ' The invalid changes cause schema validation errors.
            document.Validate(AddressOf ValidationEventHandler)

            ' Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99"

            ' Validate only the first book element. The last book
            ' element is invalid, but not included in validation.
            Dim bookNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book", manager)
            document.Validate(AddressOf ValidationEventHandler, bookNode)

        Catch ex As XmlException
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message)

        Catch ex As XmlSchemaValidationException
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message)

        Catch ex As Exception
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message)

        End Try

    End Sub

    Shared Sub ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)

        If args.Severity = XmlSeverityType.Warning Then
            Console.Write(vbCrLf & "WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write(vbCrLf & "ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)

    End Sub

End Class

En el ejemplo se toma como entrada el archivo contosoBooks.xml.The example takes the contosoBooks.xml file as input.

<?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.The example also takes the contosoBooks.xsd file as input.

<?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>

Tenga en cuenta lo siguiente a la hora de validar datos XML a medida que se cargan en el DOM.Consider the following when validating XML data as it is loaded into the DOM.

  • En el ejemplo anterior, se llama a ValidationEventHandler cada vez que se encuentra un tipo no válido.In the above example, the ValidationEventHandler is called whenever an invalid type is encountered. Si no se establece un ValidationEventHandler en el XmlReader de validación, se produce una excepción XmlSchemaValidationException cuando se llama a Load si algún atributo o tipo de elemento no se corresponde con el tipo especificado en el esquema de validación.If a ValidationEventHandler is not set on the validating XmlReader,an XmlSchemaValidationException is thrown when Load is called if any attribute or element type does not match the corresponding type specified in the validating schema.

  • Cuando se carga un documento XML en un objeto XmlDocument con un esquema asociado que define valores predeterminados, XmlDocument trata estos valores predeterminados como si aparecieran en el documento XML.When an XML document is loaded into an XmlDocument object with an associated schema that defines default values, the XmlDocument treats these defaults as if they appeared in the XML document. Esto significa que la propiedad IsEmptyElement siempre devuelve false para un elemento que tenga los valores predeterminados del esquema.This means that the IsEmptyElement property always returns false for an element that was defaulted from the schema. Aunque estuviera en el documento XML, se escribiría como un elemento vacío.Even if in the XML document, it was written as an empty element.

Validación de un documento XML en el DOMValidating an XML Document in the DOM

El método Validate de la clase XmlDocument valida los datos XML que se cargan en el DOM con los esquemas de la propiedad XmlDocument del objeto Schemas.The Validate method of the XmlDocument class validates the XML data loaded in the DOM against the schemas in the XmlDocument object's Schemas property. Después de realizar la validación correctamente, se aplican los valores predeterminados del esquema, los valores de texto se convierten en valores atómicos como sea preciso y la información de tipos se asocia a los elementos de información validados.After successful validation, schema defaults are applied, text values are converted to atomic values as necessary, and type information is associated with validated information items. Como resultado, los datos XML con tipo reemplazan a los datos XML sin tipo anteriores.As a result, typed XML data replaces previously untyped XML data.

El siguiente ejemplo es similar al ejemplo de la sección anterior "Validación de un documento XML a medida que se carga en el DOM".The example below is similar to the example in "Validating an XML Document As It Is Loaded into the DOM" above. En este ejemplo, el documento XML no se valida a medida que se carga en el DOM, sino después de cargarlo en el DOM utilizando el método Validate de la clase XmlDocument.In this example, the XML document is not validated as it is loaded into the DOM, but rather is validated after it has been loaded into the DOM using the Validate method of the XmlDocument class. El método Validate valida el documento XML con los esquemas XML contenidos en la propiedad Schemas de XmlDocument.The Validate method validates the XML document against the XML schemas contained in the Schemas property of the XmlDocument. Luego, se realizan modificaciones no válidas en el documento XML y dicho documento se vuelve a validar, lo que produce errores de validación del esquema.Invalid modifications are then made to the XML document, and the document is then revalidated, causing schema validation errors. Por último, se corrige uno de los errores y, a continuación, se valida parcialmente parte del documento XML.Finally, one of the errors is corrected, and then part of the XML document is partially validated.

using System;
using System.Xml;
using System.Xml.Schema;

class XmlDocumentValidationExample
{
    static void Main(string[] args)
    {
        try
        {
            // Create a new XmlDocument instance and load
            // the XML document into the DOM.
            XmlDocument document = new XmlDocument();
            document.Load("contosoBooks.xml");

            // Add the XML schema for the XML document to the
            // Schemas property of the XmlDocument.
            document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");

            // Validate the XML document loaded into the DOM.
            document.Validate(ValidationEventHandler);

            // Make an invalid change to the first and last 
            // price elements in the XML document, and write
            // the XmlSchemaInfo values assigned to the price
            // element during validation to the console.
            XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
            manager.AddNamespace("bk", "http://www.contoso.com/books");

            XmlNode priceNode = document.SelectSingleNode(@"/bk:bookstore/bk:book/bk:price", manager);

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault);
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil);
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement);
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType);
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity);

            priceNode.InnerXml = "A";

            XmlNodeList priceNodes = document.SelectNodes(@"/bk:bookstore/bk:book/bk:price", manager);
            XmlNode lastprice = priceNodes[priceNodes.Count - 1];
            
            lastprice.InnerXml = "B";

            // Validate the XML document with the invalid changes.
            // The invalid changes cause schema validation errors.
            document.Validate(ValidationEventHandler);

            // Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99";

            // Validate only the first book element. The last book
            // element is invalid, but not included in validation.
            XmlNode bookNode = document.SelectSingleNode(@"/bk:bookstore/bk:book", manager);
            document.Validate(ValidationEventHandler, bookNode);
        }
        catch (XmlException ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message);
        }
        catch(XmlSchemaValidationException ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message);
        }
    }

    static void ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("\nWARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("\nERROR: ");

        Console.WriteLine(args.Message);
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlDocumentValidationExample

    Shared Sub Main()

        Try

            ' Create a new XmlDocument instance and load
            ' the XML document into the DOM.
            Dim document As XmlDocument = New XmlDocument()
            document.Load("contosoBooks.xml")

            ' Add the XML schema for the XML document to the
            ' Schemas property of the XmlDocument.
            document.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")

            ' Validate the XML document loaded into the DOM.
            document.Validate(AddressOf ValidationEventHandler)

            ' Make an invalid change to the first and last 
            ' price elements in the XML document, and write
            ' the XmlSchemaInfo values assigned to the price
            ' element during validation to the console.
            Dim manager As XmlNamespaceManager = New XmlNamespaceManager(document.NameTable)
            manager.AddNamespace("bk", "http://www.contoso.com/books")

            Dim priceNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book/bk:price", manager)

            Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault)
            Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil)
            Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement)
            Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType)
            Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity)

            priceNode.InnerXml = "A"

            Dim priceNodes As XmlNodeList = document.SelectNodes("/bk:bookstore/bk:book/bk:price", manager)
            Dim lastprice As XmlNode = priceNodes(priceNodes.Count - 1)

            lastprice.InnerXml = "B"

            ' Validate the XML document with the invalid changes.
            ' The invalid changes cause schema validation errors.
            document.Validate(AddressOf ValidationEventHandler)

            ' Correct the invalid change to the first price element.
            priceNode.InnerXml = "8.99"

            ' Validate only the first book element. The last book
            ' element is invalid, but not included in validation.
            Dim bookNode As XmlNode = document.SelectSingleNode("/bk:bookstore/bk:book", manager)
            document.Validate(AddressOf ValidationEventHandler, bookNode)

        Catch ex As XmlException
            Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message)

        Catch ex As XmlSchemaValidationException
            Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message)

        Catch ex As Exception
            Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message)

        End Try

    End Sub

    Shared Sub ValidationEventHandler(ByVal sender As Object, ByVal args As ValidationEventArgs)

        If args.Severity = XmlSeverityType.Warning Then
            Console.Write(vbCrLf & "WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write(vbCrLf & "ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)

    End Sub

End Class

En el ejemplo se toman como entrada los archivos contosoBooks.xml y contosoBooks.xsd que se mencionan en la sección anterior "Validación de un documento XML a medida que se carga en el DOM".The example takes as input the contosoBooks.xml and contosoBooks.xsd files referred to in "Validating an XML Document as it is Loaded into the DOM" above.

Control de advertencias y errores de validaciónHandling Validation Errors and Warnings

Los errores de validación de esquemas XML se presentan durante la validación de datos XML cargados en el DOM.XML schema validation errors are reported when validating XML data loaded in the DOM. Todos los errores de validación de esquemas se le notifican mientras se validan los datos a medida que se cargan o cuando se valida un documento XML que no estuviera previamente validado.You are notified about all schema validation errors found while validating the XML data as it is being loaded, or when validating a previously unvalidated XML document.

ValidationEventHandler controla los errores de validación.Validation errors are handled by the ValidationEventHandler. Si se ha asignado un ValidationEventHandler a la instancia de XmlReaderSettings o se ha pasado al método Validate de la clase XmlDocument, el ValidationEventHandler controlará los errores de validación de esquemas; de lo contrario, se inicia una XmlSchemaValidationException cuando se encuentra un error de validación de esquema.If a ValidationEventHandler was assigned to the XmlReaderSettings instance, or passed to the Validate method of the XmlDocument class, the ValidationEventHandler will handle schema validation errors; otherwise an XmlSchemaValidationException is raised when a schema validation error is encountered.

Nota

Los datos XML se cargan en el DOM a pesar de los errores de validación de esquemas, a menos que ValidationEventHandler inicie una excepción para detener el proceso.The XML data is loaded into the DOM despite schema validation errors unless your ValidationEventHandler raises an exception to stop the process.

No se notifican advertencias de validación de esquemas a menos que se especifique la marca ReportValidationWarnings para el objeto XmlReaderSettings.Schema validation warnings are not reported unless the ReportValidationWarnings flag is specified to the XmlReaderSettings object.

Para ver ejemplos sobre ValidationEventHandler, vea las secciones "Validación de un documento XML a medida que se carga en el DOM" y "Validación de un documento XML en el DOM".For examples illustrating the ValidationEventHandler, see "Validating an XML Document As It Is Loaded into the DOM" and "Validating an XML Document in the DOM" above.

Vea tambiénSee also