Export (0) Print
Expand All

XmlSchemaValidator Class

Represents an XML Schema Definition Language (XSD) Schema validation engine. The XmlSchemaValidator class cannot be inherited.

System.Object
  System.Xml.Schema.XmlSchemaValidator

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

public sealed class XmlSchemaValidator

The XmlSchemaValidator type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkXmlSchemaValidatorInitializes a new instance of the XmlSchemaValidator class.
Top

  NameDescription
Public propertySupported by the XNA FrameworkLineInfoProviderGets or sets the line number information for the XML node being validated.
Public propertySupported by the XNA FrameworkSourceUriGets or sets the source URI for the XML node being validated.
Public propertySupported by the XNA FrameworkValidationEventSenderGets or sets the object sent as the sender object of a validation event.
Public propertySupported by the XNA FrameworkXmlResolverSets the XmlResolver object used to resolve xs:import and xs:include elements as well as xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes.
Top

  NameDescription
Public methodSupported by the XNA FrameworkAddSchemaAdds an XML Schema Definition Language (XSD) schema to the set of schemas used for validation.
Public methodSupported by the XNA FrameworkEndValidationEnds validation and checks identity constraints for the entire XML document.
Public methodSupported by the XNA FrameworkEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetExpectedAttributesReturns the expected attributes for the current element context.
Public methodSupported by the XNA FrameworkGetExpectedParticlesReturns the expected particles in the current element context.
Public methodSupported by the XNA FrameworkGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetUnspecifiedDefaultAttributesValidates identity constraints on the default attributes and populates the ArrayList specified with XmlSchemaAttribute objects for any attributes with default values that have not been previously validated using the ValidateAttribute method in the element context.
Public methodSupported by the XNA FrameworkInitialize()Initializes the state of the XmlSchemaValidator object.
Public methodSupported by the XNA FrameworkInitialize(XmlSchemaObject)Initializes the state of the XmlSchemaValidator object using the XmlSchemaObject specified for partial validation.
Public methodSupported by the XNA FrameworkSkipToEndElementSkips validation of the current element content and prepares the XmlSchemaValidator object to validate content in the parent element's context.
Public methodSupported by the XNA FrameworkToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkValidateAttribute(String, String, String, XmlSchemaInfo)Validates the attribute name, namespace URI, and value in the current element context.
Public methodSupported by the XNA FrameworkValidateAttribute(String, String, XmlValueGetter, XmlSchemaInfo)Validates the attribute name, namespace URI, and value in the current element context.
Public methodSupported by the XNA FrameworkValidateElement(String, String, XmlSchemaInfo)Validates the element in the current context.
Public methodSupported by the XNA FrameworkValidateElement(String, String, XmlSchemaInfo, String, String, String, String)Validates the element in the current context with the xsi:Type, xsi:Nil, xsi:SchemaLocation, and xsi:NoNamespaceSchemaLocation attribute values specified.
Public methodSupported by the XNA FrameworkValidateEndElement(XmlSchemaInfo)Verifies if the text content of the element is valid according to its data type for elements with simple content, and verifies if the content of the current element is complete for elements with complex content.
Public methodSupported by the XNA FrameworkValidateEndElement(XmlSchemaInfo, Object)Verifies if the text content of the element specified is valid according to its data type.
Public methodSupported by the XNA FrameworkValidateEndOfAttributesVerifies whether all the required attributes in the element context are present and prepares the XmlSchemaValidator object to validate the child content of the element.
Public methodSupported by the XNA FrameworkValidateText(String)Validates whether the text string specified is allowed in the current element context, and accumulates the text for validation if the current element has simple content.
Public methodSupported by the XNA FrameworkValidateText(XmlValueGetter)Validates whether the text returned by the XmlValueGetter object specified is allowed in the current element context, and accumulates the text for validation if the current element has simple content.
Public methodSupported by the XNA FrameworkValidateWhitespace(String)Validates whether the white space in the string specified is allowed in the current element context, and accumulates the white space for validation if the current element has simple content.
Public methodSupported by the XNA FrameworkValidateWhitespace(XmlValueGetter)Validates whether the white space returned by the XmlValueGetter object specified is allowed in the current element context, and accumulates the white space for validation if the current element has simple content.
Top

  NameDescription
Public eventSupported by the XNA FrameworkValidationEventHandlerThe ValidationEventHandler that receives schema validation warnings and errors encountered during schema validation.
Top

Security noteSecurity Note
  • Do not use schemas from unknown or untrusted sources or locations. Doing so will compromise the security of your code.

  • XML schemas (including inline schemas) are inherently vulnerable to denial of service attacks; do not accept them in untrusted scenarios.

  • Schema validation error messages and exceptions may expose sensitive information about the content model or URI paths to the schema file. Be careful not to expose this information to untrusted callers.

The XmlSchemaValidator class provides an efficient, high-performance mechanism to validate XML data against XML schemas in a push-based manner. For example, the XmlSchemaValidator class allows you to validate an XML infoset in-place without having to serialize it as an XML document and then reparse the document using a validating XML reader. The XmlSchemaValidator class can also be used to build validation engines over custom XML data sources or as a way to build a validating XML writer.

For more information about the XmlSchemaValidator class, see the XmlSchemaValidator Push-Based Validation topic.

Security noteSecurity Note

The ProcessInlineSchema and ProcessSchemaLocation validation flags of an XmlSchemaValidator object are not set be default. Additionally, the XmlResolver property of an XmlSchemaValidator object is null by default. As a result, external schemas referenced in include, imports, or redefine elements are not resolved by default.

The following example validates the contosoBooks.xml file against the contosoBooks.xsd schema. The example uses the XmlSerializer class to deserialize the contosoBooks.xml file and pass the value of the nodes to the methods of the XmlSchemaValidator class.

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

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>

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

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

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

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft