Export (0) Print
Expand All

Extensions.Validate Method (XAttribute, XmlSchemaObject, XmlSchemaSet, ValidationEventHandler, Boolean)

Validates that an XAttribute conforms to a specified XmlSchemaObject and an XmlSchemaSet, optionally populating the XML tree with the post-schema-validation infoset (PSVI).

Namespace:  System.Xml.Schema
Assembly:  System.Xml.Linq (in System.Xml.Linq.dll)

public static void Validate(
	this XAttribute source,
	XmlSchemaObject partialValidationType,
	XmlSchemaSet schemas,
	ValidationEventHandler validationEventHandler,
	bool addSchemaInfo
)

Parameters

source
Type: System.Xml.Linq.XAttribute

The XAttribute to validate.

partialValidationType
Type: System.Xml.Schema.XmlSchemaObject

An XmlSchemaObject that specifies the sub-tree to validate.

schemas
Type: System.Xml.Schema.XmlSchemaSet

An XmlSchemaSet to validate against.

validationEventHandler
Type: System.Xml.Schema.ValidationEventHandler

A ValidationEventHandler for an event that occurs when the reader encounters validation errors. If null, throws an exception upon validation errors.

addSchemaInfo
Type: System.Boolean

A Boolean indicating whether to populate the post-schema-validation infoset (PSVI).

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type XAttribute. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).

ExceptionCondition
XmlSchemaValidationException

Thrown for XML Schema Definition Language (XSD) validation errors.

You can use this method to validate that an XAttribute conforms to a schema. You typically use this method when you have modified an attribute, and you want to make sure that it still conforms to its schema. You could validate the entire document, but it takes less processing time to validate just the attribute.

If addSchemaInfo is true, this method populates the attribute with the post-schema-validation infoset (PSVI). After you have populated the XML tree with the PSVI, you can call Extensions.GetSchemaInfo on the validated attribute. This is useful if you are writing code that relies on data returned by GetSchemaInfo.

If you pass null for validationEventHandler, then this method raises an exception upon validation errors. Validation warnings will not raise an exception.

To validate an attribute, you use an instance of XmlSchemaObject. You can obtain this instance in various ways. An easy way is as follows:

  1. Validate that a document conforms to a schema.

  2. Add the post-schema-validation infoset (PSVI) by calling the Validate extension method.

  3. Call the GetSchemaInfo extension method to retrieve an object that implements IXmlSchemaInfo. From the retrieved object, you can get an XmlSchemaObject.

After you have an instance of an XmlSchemaObject, you can use this method to validate an attribute.

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);
}

This example produces the following output:

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

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft