Extensions.Validate Método

Definición

Valida que un XDocument, un XElement o un XAttribute se ajusta a un XSD en un XmlSchemaSet.

Sobrecargas

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

Este método valida que un XDocument se ajusta a un XSD en un XmlSchemaSet.

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Este método valida que un XAttribute se ajusta a un XmlSchemaObject especificado y un XmlSchemaSet.

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

Valida que XDocument se ajusta a XSD en XmlSchemaSet y, de manera opcional, rellena el árbol XML con el conjunto de información posterior a la validación del esquema (PSVI).

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Este método valida que un subárbol XElement se ajusta a un XmlSchemaObject especificado y a un XmlSchemaSet.

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)

Valida que XAttribute se ajusta a un XmlSchemaObject especificado y a un XmlSchemaSet y, de manera opcional, rellena el árbol XML con el conjunto de información posterior a la validación del esquema (PSVI).

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)

Valida que un subárbol XElement se ajusta a un XmlSchemaObject especificado y a un XmlSchemaSet y, de manera opcional, rellena el árbol XML con el conjunto de información posterior a la validación del esquema (PSVI).

Comentarios

Estos métodos usan un subyacente XmlReader para validar el árbol XML con un XSD.

Los mensajes de error y advertencia de validación se controlan mediante el ValidationEventHandler delegado . Si no se proporciona ningún controlador de eventos a estos métodos, los errores de validación se exponen como .XmlSchemaValidationException Las advertencias de validación no provocan que se produzca una XmlSchemaValidationException excepción .

Algunos de estos métodos de extensión permiten opcionalmente el rellenado del conjunto de información posterior a la validación del esquema (PSVI).

Validate(XDocument, XmlSchemaSet, ValidationEventHandler)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

Este método valida que un XDocument se ajusta a un XSD en un XmlSchemaSet.

C#
public static void Validate (this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler);
C#
public static void Validate (this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler);

Parámetros

source
XDocument

Objeto XDocument que se va a validar.

schemas
XmlSchemaSet

Objeto XmlSchemaSet con el que se va a validar.

validationEventHandler
ValidationEventHandler

ValidationEventHandler de un evento que se provoca cuando el lector detecta errores de validación. Si es null, se produce una excepción en los errores de validación.

Excepciones

Se produce para los errores de validación del lenguaje de definición de esquemas XML (XSD).

Ejemplos

En el ejemplo siguiente se crea un XmlSchemaSet, a continuación, se validan dos objetos XDocument con el esquema establecido. Uno de los documentos es válido, el otro no.

C#
                string xsdMarkup =  
    @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
       <xsd:element name='Root'>  
        <xsd:complexType>  
         <xsd:sequence>  
          <xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>  
          <xsd:element name='Child2' minOccurs='1' maxOccurs='1'/>  
         </xsd:sequence>  
        </xsd:complexType>  
       </xsd:element>  
      </xsd:schema>";  
XmlSchemaSet schemas = new XmlSchemaSet();  
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));  

XDocument doc1 = new XDocument(  
    new XElement("Root",  
        new XElement("Child1", "content1"),  
        new XElement("Child2", "content1")  
    )  
);  

XDocument doc2 = new XDocument(  
    new XElement("Root",  
        new XElement("Child1", "content1"),  
        new XElement("Child3", "content1")  
    )  
);  

Console.WriteLine("Validating doc1");  
bool errors = false;  
doc1.Validate(schemas, (o, e) =>  
                     {  
                         Console.WriteLine("{0}", e.Message);  
                         errors = true;  
                     });  
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");  

Console.WriteLine();  
Console.WriteLine("Validating doc2");  
errors = false;  
doc2.Validate(schemas, (o, e) =>  
                     {  
                         Console.WriteLine("{0}", e.Message);  
                         errors = true;  
                     });  
Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated");  

Este ejemplo produce el siguiente resultado:

Validating doc1  
doc1 validated  

Validating doc2  
The element 'Root' has invalid child element 'Child3'. List of possible elements expected: 'Child2'.  
doc2 did not validate  

Comentarios

Este método de extensión valida que XDocument se ajusta al modelo de contenido del esquema en XmlSchemaSet.

Se aplica a

.NET 9 otras versiones
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 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

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

Este método valida que un XAttribute se ajusta a un XmlSchemaObject especificado y un XmlSchemaSet.

C#
public static void Validate (this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler);
C#
public static void Validate (this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler);

Parámetros

source
XAttribute

Objeto XAttribute que se va a validar.

partialValidationType
XmlSchemaObject

Objeto XmlSchemaObject que especifica el subárbol que se va a validar.

schemas
XmlSchemaSet

Objeto XmlSchemaSet con el que se va a validar.

validationEventHandler
ValidationEventHandler

ValidationEventHandler de un evento que se provoca cuando el lector detecta errores de validación. Si es null, se produce una excepción en los errores de validación.

Excepciones

Se produce para los errores de validación del lenguaje de definición de esquemas XML (XSD).

Ejemplos

C#
                string xsdMarkup =  
    @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
       <xsd:element name='Root'>  
        <xsd:complexType>  
         <xsd:simpleContent>  
          <xsd:extension base='xsd:string'>  
           <xsd:attribute name='Lang' use='required'>  
            <xsd:simpleType>  
             <xsd:restriction base='xsd:token'>  
              <xsd:enumeration value='C#'/>  
              <xsd:enumeration value='VB'/>  
             </xsd:restriction>  
            </xsd:simpleType>  
           </xsd:attribute>  
          </xsd:extension>  
         </xsd:simpleContent>  
        </xsd:complexType>  
       </xsd:element>  
      </xsd:schema>";  

XmlSchemaSet schemas = new XmlSchemaSet();  
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));  

XDocument doc1 = new XDocument(  
    new XElement("Root",  
        new XAttribute("Lang", "C#")  
    )  
);  

Console.WriteLine("Validating doc1 ...");  
bool errors = false;  
doc1.Validate(schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    }, true);  
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");  

Console.WriteLine();  
Console.WriteLine("Validating Lang attribute ...");  
XAttribute lang = doc1.Root.Attribute("Lang");  

errors = false;  
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    });  
Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");  

// the following makes the Lang attribute invalid according to the schema  
lang.Value = "VC";  

Console.WriteLine();  
Console.WriteLine("Validating Lang attribute ...");  

errors = false;  
lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    });  
Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");  

Este ejemplo produce el siguiente resultado:

Validating doc1 ...  
doc1 validated  

Validating Lang attribute ...  
lang validated  

Validating Lang attribute ...  
The 'Lang' attribute is invalid - The value 'VC' is invalid according to its datatype 'Token' - The Enumeration constraint failed.  
lang did not validate  

Comentarios

Puede usar este método para validar que XAttribute se ajusta a un esquema. Normalmente, se usa este método cuando se ha modificado un atributo y se desea asegurarse de que sigue siendo conforme a su esquema. Puede validar todo el documento, pero se tarda menos tiempo de procesamiento en validar solo el atributo.

Si pasa null para validationEventHandler, este método genera una excepción tras los errores de validación. Las advertencias de validación no generarán una excepción.

Para validar un atributo, use una instancia de XmlSchemaObject. Puede obtener esta instancia de varias maneras. Una manera sencilla es la siguiente:

  1. Compruebe que un documento se ajusta a un esquema.

  2. Agregue el conjunto de información posterior a la validación del esquema (PSVI) llamando al método de Validate extensión.

  3. Llame al método de GetSchemaInfo extensión para recuperar un objeto que implementa IXmlSchemaInfo. Desde el objeto recuperado, puede obtener un XmlSchemaObject.

Después de tener una instancia de , XmlSchemaObjectpuede usar este método para validar un atributo.

Se aplica a

.NET 9 otras versiones
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 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

Validate(XDocument, XmlSchemaSet, ValidationEventHandler, Boolean)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

Valida que XDocument se ajusta a XSD en XmlSchemaSet y, de manera opcional, rellena el árbol XML con el conjunto de información posterior a la validación del esquema (PSVI).

C#
public static void Validate (this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler, bool addSchemaInfo);
C#
public static void Validate (this System.Xml.Linq.XDocument source, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo);

Parámetros

source
XDocument

Objeto XDocument que se va a validar.

schemas
XmlSchemaSet

Objeto XmlSchemaSet con el que se va a validar.

validationEventHandler
ValidationEventHandler

ValidationEventHandler de un evento que se provoca cuando el lector detecta errores de validación. Si es null, se produce una excepción en los errores de validación.

addSchemaInfo
Boolean

Boolean que indica si se rellena el conjunto de información posterior a la validación del esquema (PSVI).

Excepciones

Se produce para los errores de validación del lenguaje de definición de esquemas XML (XSD).

Ejemplos

El ejemplo siguiente contiene un XSD que define el Child2 elemento con un atributo con un Att1 valor predeterminado. Después de validar correctamente el documento, el atributo con el valor predeterminado se agrega al árbol XML. Tenga en cuenta que el atributo predeterminado no se agrega a doc2, que no se valida con el esquema.

C#
                string xsdMarkup =  
    @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
       <xsd:element name='Root'>  
        <xsd:complexType>  
         <xsd:sequence>  
          <xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>  
          <xsd:element name='Child2' minOccurs='1' maxOccurs='1'>  
           <xsd:complexType>  
            <xsd:simpleContent>  
             <xsd:extension base='xsd:string'>  
              <xsd:attribute name='Att1' default='Att1 Default Value'/>  
             </xsd:extension>  
            </xsd:simpleContent>  
           </xsd:complexType>  
          </xsd:element>  
         </xsd:sequence>  
        </xsd:complexType>  
       </xsd:element>  
      </xsd:schema>";  
XmlSchemaSet schemas = new XmlSchemaSet();  
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));  

XDocument doc1 = new XDocument(  
    new XElement("Root",  
        new XElement("Child1", "c1"),  
        new XElement("Child2", "c2")  
    )  
);  

XDocument doc2 = new XDocument(  
    new XElement("Root",  
        new XElement("Child1", "content1"),  
        new XElement("Child3", "content1")  
    )  
);  

Console.WriteLine("Validating doc1");  
bool errors = false;  
doc1.Validate(schemas, (o, e) =>  
                           {  
                               Console.WriteLine("{0}", e.Message);  
                               errors = true;  
                           }, true);  
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");  

Console.WriteLine();  
Console.WriteLine("Validating doc2");  
errors = false;  
doc2.Validate(schemas, (o, e) =>  
                     {  
                         Console.WriteLine("{0}", e.Message);  
                         errors = true;  
                     }, true);  
Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated");  

Console.WriteLine();  
Console.WriteLine("Contents of doc1:");  
Console.WriteLine(doc1);  

Console.WriteLine();  
Console.WriteLine("Contents of doc2:");  
Console.WriteLine(doc2);  

Este ejemplo produce el siguiente resultado:

Validating doc1  
doc1 validated  

Validating doc2  
The element 'Root' has invalid child element 'Child3'. List of possible elements expected: 'Child2'.  
doc2 did not validate  

Contents of doc1:  
<Root>  
  <Child1>c1</Child1>  
  <Child2 Att1="Att1 Default Value">c2</Child2>  
</Root>  

Contents of doc2:  
<Root>  
  <Child1>content1</Child1>  
  <Child3>content1</Child3>  
</Root>  

En el ejemplo siguiente se rellena el árbol con PSVI. Después de la validación, imprime todos los elementos y atributos del árbol que no son válidos según psvi.

C#
                static void DumpInvalidNodes(XElement el)  
{  
    if (el.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)  
        Console.WriteLine("Invalid Element {0}",  
            el.AncestorsAndSelf()  
            .InDocumentOrder()  
            .Aggregate("", (s, i) => s + "/" + i.Name.ToString()));  
    foreach (XAttribute att in el.Attributes())  
        if (att.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)  
            Console.WriteLine("Invalid Attribute {0}",  
                att  
                .Parent  
                .AncestorsAndSelf()  
                .InDocumentOrder()  
                .Aggregate("",  
                    (s, i) => s + "/" + i.Name.ToString()) + "/@" + att.Name.ToString()  
                );  
    foreach (XElement child in el.Elements())  
        DumpInvalidNodes(child);  
}  

static void Main(string[] args)  
{  
   string xsdMarkup =  
        @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
           <xsd:simpleType name='GCType'>  
            <xsd:restriction base='xsd:token'>  
             <xsd:enumeration value='AAA'/>  
             <xsd:enumeration value='BBB'/>  
            </xsd:restriction>  
           </xsd:simpleType>  
           <xsd:element name='Root'>  
            <xsd:complexType>  
             <xsd:sequence>  
              <xsd:element name='Child1' minOccurs='1' maxOccurs='1'>  
               <xsd:complexType>  
                <xsd:sequence>  
                 <xsd:element name='GrandChild1' type='GCType'/>  
                 <xsd:element name='GrandChild2' type='GCType'/>  
                 <xsd:element name='GrandChild3' type='GCType'/>  
                </xsd:sequence>  
               </xsd:complexType>  
              </xsd:element>  
             </xsd:sequence>  
            </xsd:complexType>  
           </xsd:element>  
          </xsd:schema>";  

    XmlSchemaSet schemas = new XmlSchemaSet();  
    schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));  

    XDocument doc1 = new XDocument(  
        new XElement("Root",  
            new XElement("Child1",  
                new XElement("GrandChild1", "AAA"),  
                new XElement("GrandChild2", "ZZZ"),  
                new XElement("GrandChild3", "ZZZ")  
            )  
        )  
    );  

    Console.WriteLine("Validating doc1 ...");  
    bool errors = false;  
    doc1.Validate(schemas, (sender, e) =>  
        {  
            Console.WriteLine(e.Message);  
            errors = true;  
        }, true);  
    Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");  
    DumpInvalidNodes(doc1.Root);  
}  

Este ejemplo produce el siguiente resultado:

Validating doc1 ...  
The 'GrandChild2' element is invalid - The value 'ZZZ' is invalid according to its datatype 'GCType' - The Enumeration constraint failed.  
The 'GrandChild3' element is invalid - The value 'ZZZ' is invalid according to its datatype 'GCType' - The Enumeration constraint failed.  
doc1 did not validate  
Invalid Element /Root  
Invalid Element /Root/Child1  
Invalid Element /Root/Child1/GrandChild2  
Invalid Element /Root/Child1/GrandChild3  

Comentarios

Este método de extensión valida que XDocument se ajusta al modelo de contenido del esquema en XmlSchemaSet.

Si addSchemaInfo es true, este método rellena el árbol XML con el conjunto de información posterior a la validación del esquema (PSVI).

Hay dos pasos para rellenar el árbol XML con PSVI.

  1. En primer lugar, se agrega una anotación a todos los nodos del árbol para permitirle llamar Extensions.GetSchemaInfo a un Extensions.GetSchemaInfo elemento o atributo en el árbol.

  2. En segundo lugar, los elementos y atributos predeterminados definidos en el XSD se agregan al árbol XML. Al llamar a uno de los GetSchemaInfo métodos, puede determinar si se agregó un elemento o atributo específico desde el XSD como un elemento o atributo predeterminados.

Se aplica a

.NET 9 otras versiones
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 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

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

Este método valida que un subárbol XElement se ajusta a un XmlSchemaObject especificado y a un XmlSchemaSet.

C#
public static void Validate (this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler);
C#
public static void Validate (this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler);

Parámetros

source
XElement

Objeto XElement que se va a validar.

partialValidationType
XmlSchemaObject

Objeto XmlSchemaObject que especifica el subárbol que se va a validar.

schemas
XmlSchemaSet

Objeto XmlSchemaSet con el que se va a validar.

validationEventHandler
ValidationEventHandler

ValidationEventHandler de un evento que se provoca cuando el lector detecta errores de validación. Si es null, se produce una excepción en los errores de validación.

Excepciones

Se produce para los errores de validación del lenguaje de definición de esquemas XML (XSD).

Ejemplos

C#
                string xsdMarkup =  
    @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
       <xsd:element name='Root'>  
        <xsd:complexType>  
         <xsd:sequence>  
          <xsd:element name='Child1' minOccurs='1' maxOccurs='1'>  
           <xsd:complexType>  
            <xsd:sequence>  
             <xsd:element name='GrandChild1' minOccurs='1' maxOccurs='1'/>  
             <xsd:element name='GrandChild2' minOccurs='1' maxOccurs='2'/>  
            </xsd:sequence>  
           </xsd:complexType>  
          </xsd:element>  
         </xsd:sequence>  
        </xsd:complexType>  
       </xsd:element>  
      </xsd:schema>";  

XmlSchemaSet schemas = new XmlSchemaSet();  
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));  

XDocument doc1 = new XDocument(  
    new XElement("Root",  
        new XElement("Child1",  
            new XElement("GrandChild1", "gc"),  
            new XElement("GrandChild2", "gc")  
        )  
    )  
);  

Console.WriteLine("Validating doc1 ...");  
bool errors = false;  
doc1.Validate(schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    }, true);  
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");  

Console.WriteLine();  
Console.WriteLine("Validating Child1 after first edit ...");  
XElement child1 = doc1.Element("Root").Element("Child1");  
child1.Add(new XElement("GrandChild2", "gc"));  
errors = false;  
child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    });  
Console.WriteLine("child1 {0}", errors ? "did not validate" : "validated");  

// the following makes the Child1 element invalid according to the schema  
child1.Add(new XElement("GrandChild3", "gc"));  
Console.WriteLine();  
Console.WriteLine("Validating Child1 after second edit ...");  
child1.Validate(child1.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    });  
Console.WriteLine("child1 {0}", errors ? "did not validate" : "validated");  

Este ejemplo produce el siguiente resultado:

Validating doc1 ...  
doc1 validated  

Validating Child1 after first edit ...  
child1 validated  

Validating Child1 after second edit ...  
The element 'Child1' has invalid child element 'GrandChild3'.  
child1 did not validate  

Comentarios

Puede usar este método para validar que un subárbol (con una XElement en su raíz) se ajusta a un esquema. Normalmente, se usa este método cuando se ha modificado un subárbol y se desea asegurarse de que sigue siendo conforme a su esquema. Puede validar todo el documento, pero tarda menos tiempo en procesarse para validar un solo subárbol.

Si pasa null para validationEventHandler, este método genera una excepción tras los errores de validación. Las advertencias de validación no generarán una excepción.

Para validar un subárbol, use una instancia de XmlSchemaObject. Puede obtener esta instancia de varias maneras. Una manera sencilla es la siguiente:

  1. Compruebe que un documento se ajusta a un esquema.

  2. Agregue el conjunto de información posterior a la validación del esquema (PSVI) llamando al método de Validate extensión.

  3. Llame al método de GetSchemaInfo extensión para recuperar un objeto que implementa IXmlSchemaInfo. Desde el objeto recuperado, puede obtener un XmlSchemaObject.

Después de tener una instancia de , XmlSchemaObjectpuede usar este método para validar un subárbol.

Se aplica a

.NET 9 otras versiones
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 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

Validate(XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

Valida que XAttribute se ajusta a un XmlSchemaObject especificado y a un XmlSchemaSet y, de manera opcional, rellena el árbol XML con el conjunto de información posterior a la validación del esquema (PSVI).

C#
public static void Validate (this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler, bool addSchemaInfo);
C#
public static void Validate (this System.Xml.Linq.XAttribute source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo);

Parámetros

source
XAttribute

Objeto XAttribute que se va a validar.

partialValidationType
XmlSchemaObject

Objeto XmlSchemaObject que especifica el subárbol que se va a validar.

schemas
XmlSchemaSet

Objeto XmlSchemaSet con el que se va a validar.

validationEventHandler
ValidationEventHandler

ValidationEventHandler de un evento que se provoca cuando el lector detecta errores de validación. Si es null, se produce una excepción en los errores de validación.

addSchemaInfo
Boolean

Boolean que indica si se rellena el conjunto de información posterior a la validación del esquema (PSVI).

Excepciones

Se produce para los errores de validación del lenguaje de definición de esquemas XML (XSD).

Ejemplos

C#
                static void DumpInvalidNodes(XElement el)  
{  
    if (el.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)  
        Console.WriteLine("Invalid Element {0}",  
            el.AncestorsAndSelf()  
            .InDocumentOrder()  
            .Aggregate("", (s, i) => s + "/" + i.Name.ToString()));  
    foreach (XAttribute att in el.Attributes())  
        if (att.GetSchemaInfo().Validity != XmlSchemaValidity.Valid)  
            Console.WriteLine("Invalid Attribute {0}",  
                att  
                .Parent  
                .AncestorsAndSelf()  
                .InDocumentOrder()  
                .Aggregate("",  
                    (s, i) => s + "/" + i.Name.ToString()) + "/@" + att.Name.ToString()  
                );  
    foreach (XElement child in el.Elements())  
        DumpInvalidNodes(child);  
}  

static void Main(string[] args)  
{  
    string xsdMarkup =  
        @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
       <xsd:element name='Root'>  
        <xsd:complexType>  
         <xsd:simpleContent>  
          <xsd:extension base='xsd:string'>  
           <xsd:attribute name='Lang' use='required'>  
            <xsd:simpleType>  
             <xsd:restriction base='xsd:token'>  
              <xsd:enumeration value='C#'/>  
              <xsd:enumeration value='VB'/>  
             </xsd:restriction>  
            </xsd:simpleType>  
           </xsd:attribute>  
          </xsd:extension>  
         </xsd:simpleContent>  
        </xsd:complexType>  
       </xsd:element>  
      </xsd:schema>";  

    XmlSchemaSet schemas = new XmlSchemaSet();  
    schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));  

    XDocument doc1 = new XDocument(  
        new XElement("Root",  
            new XAttribute("Lang", "C#")  
        )  
    );  

    Console.WriteLine("Validating doc1 ...");  
    bool errors = false;  
    doc1.Validate(schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    }, true);  
    Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");  
    DumpInvalidNodes(doc1.Root);  

    Console.WriteLine();  
    Console.WriteLine("Validating Lang attribute ...");  
    XAttribute lang = doc1.Element("Root").Attribute("Lang");  

    errors = false;  
    lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    }, true);  
    Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");  
    DumpInvalidNodes(doc1.Root);  

    // the following makes the Lang attribute invalid according to the schema  
    lang.Value = "VC";  

    Console.WriteLine();  
    Console.WriteLine("Validating Lang attribute ...");  

    errors = false;  
    lang.Validate(lang.GetSchemaInfo().SchemaAttribute, schemas, (sender, e) =>  
    {  
        Console.WriteLine(e.Message);  
        errors = true;  
    }, true);  
    Console.WriteLine("lang {0}", errors ? "did not validate" : "validated");  
    DumpInvalidNodes(doc1.Root);  
}  

Este ejemplo produce el siguiente resultado:

Validating doc1 ...  
doc1 validated  

Validating Lang attribute ...  
lang validated  

Validating Lang attribute ...  
The 'Lang' attribute is invalid - The value 'VC' is invalid according to its datatype 'Token' - The Enumeration constraint failed.  
lang did not validate  
Invalid Attribute /Root/@Lang  

Comentarios

Puede usar este método para validar que XAttribute se ajusta a un esquema. Normalmente, se usa este método cuando se ha modificado un atributo y se desea asegurarse de que sigue siendo conforme a su esquema. Puede validar todo el documento, pero se tarda menos tiempo en procesarse para validar solo el atributo.

Si addSchemaInfo es true, este método rellena el atributo con el conjunto de información posterior a la validación del esquema (PSVI). Una vez que haya rellenado el árbol XML con psvi, puede llamar al Extensions.GetSchemaInfo atributo validado. Esto resulta útil si está escribiendo código que se basa en los datos devueltos por GetSchemaInfo.

Si pasa null para validationEventHandler, este método genera una excepción tras los errores de validación. Las advertencias de validación no generarán una excepción.

Para validar un atributo, use una instancia de XmlSchemaObject. Puede obtener esta instancia de varias maneras. Una manera sencilla es la siguiente:

  1. Compruebe que un documento se ajusta a un esquema.

  2. Agregue el conjunto de información posterior a la validación del esquema (PSVI) mediante una llamada al método de Validate extensión.

  3. Llame al método de GetSchemaInfo extensión para recuperar un objeto que implementa IXmlSchemaInfo. Desde el objeto recuperado, puede obtener un XmlSchemaObject.

Después de tener una instancia de , XmlSchemaObjectpuede usar este método para validar un atributo.

Se aplica a

.NET 9 otras versiones
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 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

Validate(XElement, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)

Source:
XNodeValidator.cs
Source:
XNodeValidator.cs
Source:
XNodeValidator.cs

Valida que un subárbol XElement se ajusta a un XmlSchemaObject especificado y a un XmlSchemaSet y, de manera opcional, rellena el árbol XML con el conjunto de información posterior a la validación del esquema (PSVI).

C#
public static void Validate (this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler? validationEventHandler, bool addSchemaInfo);
C#
public static void Validate (this System.Xml.Linq.XElement source, System.Xml.Schema.XmlSchemaObject partialValidationType, System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.ValidationEventHandler validationEventHandler, bool addSchemaInfo);

Parámetros

source
XElement

Objeto XElement que se va a validar.

partialValidationType
XmlSchemaObject

Objeto XmlSchemaObject que especifica el subárbol que se va a validar.

schemas
XmlSchemaSet

Objeto XmlSchemaSet con el que se va a validar.

validationEventHandler
ValidationEventHandler

ValidationEventHandler de un evento que se provoca cuando el lector detecta errores de validación. Si es null, se produce una excepción en los errores de validación.

addSchemaInfo
Boolean

Boolean que indica si se rellena el conjunto de información posterior a la validación del esquema (PSVI).

Excepciones

Se produce para los errores de validación del lenguaje de definición de esquemas XML (XSD).

Ejemplos

C#
                string xsdMarkup =  
    @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>  
       <xsd:element name='Root'>  
        <xsd:complexType>  
         <xsd:sequence>  
          <xsd:element name='Child1' minOccurs='1' maxOccurs='1'/>  
          <xsd:element name='Child2' minOccurs='1' maxOccurs='1'>  
           <xsd:complexType>  
            <xsd:simpleContent>  
             <xsd:extension base='xsd:string'>  
              <xsd:attribute name='Att1' default='Att1 Default Value'/>  
             </xsd:extension>  
            </xsd:simpleContent>  
           </xsd:complexType>  
          </xsd:element>  
         </xsd:sequence>  
        </xsd:complexType>  
       </xsd:element>  
      </xsd:schema>";  
XmlSchemaSet schemas = new XmlSchemaSet();  
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));  

XDocument doc1 = new XDocument(  
    new XElement("Root",  
        new XElement("Child1", "c1"),  
        new XElement("Child2", "c2")  
    )  
);  

XDocument doc2 = new XDocument(  
    new XElement("Root",  
        new XElement("Child1", "content1"),  
        new XElement("Child3", "content1")  
    )  
);  

Console.WriteLine("Validating doc1");  
bool errors = false;  
doc1.Validate(schemas, (o, e) =>  
                     {  
                         Console.WriteLine("{0}", e.Message);  
                         errors = true;  
                     }, true);  
Console.WriteLine("doc1 {0}", errors ? "did not validate" : "validated");  

Console.WriteLine();  
Console.WriteLine("Validating doc2");  
errors = false;  
doc2.Validate(schemas, (o, e) =>  
                     {  
                         Console.WriteLine("{0}", e.Message);  
                         errors = true;  
                     }, true);  
Console.WriteLine("doc2 {0}", errors ? "did not validate" : "validated");  

Console.WriteLine();  
Console.WriteLine("Contents of doc1:");  
Console.WriteLine(doc1);  

Console.WriteLine();  
Console.WriteLine("Contents of doc2:");  
Console.WriteLine(doc2);  

Este ejemplo produce el siguiente resultado:

Validating doc1  
doc1 validated  

Validating doc2  
The element 'Root' has invalid child element 'Child3'. List of possible elements expected: 'Child2'.  
doc2 did not validate  

Contents of doc1:  
<Root>  
  <Child1>c1</Child1>  
  <Child2 Att1="Att1 Default Value">c2</Child2>  
</Root>  

Contents of doc2:  
<Root>  
  <Child1>content1</Child1>  
  <Child3>content1</Child3>  
</Root>  

Comentarios

Puede usar este método para validar que un subárbol (con una XElement en la raíz del subárbol) se ajusta a un esquema. Normalmente, se usa este método cuando se ha modificado un subárbol y se desea asegurarse de que sigue siendo conforme a su esquema. Puede validar todo el documento, pero se tarda menos tiempo en procesarse para validar un solo subárbol.

Si addSchemaInfo es true, este método rellena el árbol XML con el conjunto de información posterior a la validación del esquema (PSVI).

Hay dos aspectos de rellenar el árbol XML con psvi.

En primer lugar, se agrega una anotación a todos los nodos del árbol de modo que ahora puede llamar a GetSchemaInfo en un elemento o atributo del árbol.

En segundo lugar, los elementos y atributos predeterminados definidos en el XSD se agregan al árbol XML. Al llamar a uno de los GetSchemaInfo métodos, puede determinar si se agregó un elemento o atributo específico desde el XSD como un elemento o atributo predeterminados.

Si pasa null para validationEventHandler, este método genera una excepción tras los errores de validación. Las advertencias de validación no generarán una excepción.

Para validar un subárbol, use una instancia de XmlSchemaObject. Puede obtener esta instancia de varias maneras. Una manera sencilla es la siguiente:

  1. Compruebe que un documento se ajusta a un esquema.

  2. Agregue el conjunto de información posterior a la validación del esquema (PSVI) mediante una llamada al método de Validate extensión.

  3. Llame al método de GetSchemaInfo extensión para recuperar un objeto que implementa IXmlSchemaInfo. Desde el objeto recuperado, puede obtener un XmlSchemaObject.

Después de tener una instancia de , XmlSchemaObjectpuede usar este método para validar un subárbol.

Se aplica a

.NET 9 otras versiones
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 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