XmlDocument.Validate 方法

定义

验证 XmlDocument 是不是 Schemas 属性中包含的 XML 架构定义语言 (XSD) 架构。Validates the XmlDocument against the XML Schema Definition Language (XSD) schemas contained in the Schemas property.

重载

Validate(ValidationEventHandler)

验证 XmlDocument 是不是 Schemas 属性中包含的 XML 架构定义语言 (XSD) 架构。Validates the XmlDocument against the XML Schema Definition Language (XSD) schemas contained in the Schemas property.

Validate(ValidationEventHandler, XmlNode)

根据 Schemas 属性中的 XML 架构定义语言 (XSD) 架构,验证指定的 XmlNode 对象。Validates the XmlNode object specified against the XML Schema Definition Language (XSD) schemas in the Schemas property.

Validate(ValidationEventHandler)

验证 XmlDocument 是不是 Schemas 属性中包含的 XML 架构定义语言 (XSD) 架构。Validates the XmlDocument against the XML Schema Definition Language (XSD) schemas contained in the Schemas property.

public:
 void Validate(System::Xml::Schema::ValidationEventHandler ^ validationEventHandler);
public void Validate (System.Xml.Schema.ValidationEventHandler validationEventHandler);
member this.Validate : System.Xml.Schema.ValidationEventHandler -> unit
Public Sub Validate (validationEventHandler As ValidationEventHandler)

参数

validationEventHandler
ValidationEventHandler

接收有关架构验证警告和错误的信息的 ValidationEventHandler 对象。The ValidationEventHandler object that receives information about schema validation warnings and errors.

例外

发生了架构验证事件并且没有指定任何 ValidationEventHandler 对象。A schema validation event occurred and no ValidationEventHandler object was specified.

示例

下面的示例阐释了 Validate 方法的用法。The following example illustrates use of the Validate method. 该示例使用 XmlReaderSettingsXmlReader 对象创建包含关联的 XSD 架构的 XmlDocumentThe example creates an XmlDocument that contains an associated XSD schema using the XmlReaderSettings and XmlReader objects. 然后,该示例使用 XPathNavigator 类在生成架构验证错误的 XML 文档中错误地修改某个元素的类型化值。The example then uses the XPathNavigator class to incorrectly modify the typed value of an element in the XML document generating a schema validation error.

#using <System.Xml.dll>

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

class XPathValidation
{
public:

    static void Main()
    {
        try
        {
            XmlReaderSettings^ settings = gcnew XmlReaderSettings();
            settings->Schemas->Add("http://www.contoso.com/books", "contosoBooks.xsd");
            settings->ValidationType = ValidationType::Schema;

            XmlReader^ reader = XmlReader::Create("contosoBooks.xml", settings);
            XmlDocument^ document = gcnew XmlDocument();
            document->Load(reader);

            ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(ValidationEventHandlerOne);

            // the following call to Validate succeeds.
            document->Validate(eventHandler);

            // add a node so that the document is no longer valid
            XPathNavigator^ navigator = document->CreateNavigator();
            navigator->MoveToFollowing("price", "http://www.contoso.com/books");
            XmlWriter^ writer = navigator->InsertAfter();
            writer->WriteStartElement("anotherNode", "http://www.contoso.com/books");
            writer->WriteEndElement();
            writer->Close();

            // the document will now fail to successfully validate
            document->Validate(eventHandler);
        }
        catch(Exception^ ex)
        {
            Console::WriteLine(ex->Message);
        }
    }

    static void ValidationEventHandlerOne(Object^ sender, ValidationEventArgs^ e)
    {
        switch (e->Severity)
        {
        case XmlSeverityType::Error:
            Console::WriteLine("Error: {0}", e->Message);
            break;
        case XmlSeverityType::Warning:
            Console::WriteLine("Warning {0}", e->Message);
            break;
        }

    }
};

int main()
{
    XPathValidation::Main();
    Console::ReadLine();
    return 0;
};
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;

class XPathValidation
{
    static void Main()
    {
        try
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
            settings.ValidationType = ValidationType.Schema;

            XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);
            XmlDocument document = new XmlDocument();
            document.Load(reader);

            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

            // the following call to Validate succeeds.
            document.Validate(eventHandler);

            // add a node so that the document is no longer valid
            XPathNavigator navigator = document.CreateNavigator();
            navigator.MoveToFollowing("price", "http://www.contoso.com/books");
            XmlWriter writer = navigator.InsertAfter();
            writer.WriteStartElement("anotherNode", "http://www.contoso.com/books");
            writer.WriteEndElement();
            writer.Close();

            // the document will now fail to successfully validate
            document.Validate(eventHandler);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    static void ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        switch (e.Severity)
        {
            case XmlSeverityType.Error:
                Console.WriteLine("Error: {0}", e.Message);
                break;
            case XmlSeverityType.Warning:
                Console.WriteLine("Warning {0}", e.Message);
                break;
        }
    }
}
Imports System.Xml
Imports System.Xml.Schema
Imports System.Xml.XPath

Class XPathValidation

    Shared Sub Main()

        Try

            Dim settings As XmlReaderSettings = New XmlReaderSettings()
            settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd")
            settings.ValidationType = ValidationType.Schema

            Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings)
            Dim document As XmlDocument = New XmlDocument()
            document.Load(reader)

            Dim eventHandler As ValidationEventHandler = New ValidationEventHandler(AddressOf ValidationEventHandler)

            ' the following call to Validate succeeds.
            document.Validate(eventHandler)

            ' add a node so that the document is no longer valid
            Dim navigator As XPathNavigator = document.CreateNavigator()
            navigator.MoveToFollowing("price", "http://www.contoso.com/books")
            Dim writer As XmlWriter = navigator.InsertAfter()
            writer.WriteStartElement("anotherNode", "http://www.contoso.com/books")
            writer.WriteEndElement()
            writer.Close()

            ' the document will now fail to successfully validate
            document.Validate(eventHandler)

        Catch ex As Exception

            Console.WriteLine(ex.Message)

        End Try

    End Sub

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

        Select Case e.Severity
            Case XmlSeverityType.Error
                Console.WriteLine("Error: {0}", e.Message)
            Case XmlSeverityType.Warning
                Console.WriteLine("Warning {0}", e.Message)
        End Select

    End Sub

End Class

该示例使用 contosoBooks.xmlcontosoBooks.xsd 文件作为输入。The example takes the contosoBooks.xml and contosoBooks.xsd files 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>
<?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>

注解

Validate 方法根据 Schemas 属性中包含的架构验证 XmlDocument 中的 XML 数据。The Validate method validates the XML data in the XmlDocument against the schemas contained in the Schemas property. Validate 方法执行信息集补充。The Validate method performs infoset augmentation. 具体而言,在成功验证后,将应用架构默认值,根据需要将文本值转换为原子值,并将类型信息与已验证的信息项关联。Specifically, 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. 结果是 XmlDocument 中的以前未类型化的 XML 子树替换为类型化的子树。The result is a previously un-typed XML sub-tree in the XmlDocument replaced with a typed sub-tree.

下面是使用 Validate 方法时要考虑的重要注意事项。The following are important notes to consider when using the Validate method.

  • 将忽略 xsi:schemaLocationxsi:noNamespaceSchemaLocation 之类的架构位置提示。Schema location hints like xsi:schemaLocation or xsi:noNamespaceSchemaLocation are ignored.

  • 将忽略内联架构。Inline schemas are ignored.

  • 如果在验证期间发生架构验证错误,则 XmlDocument 将通过某些具有正确类型信息的节点进行部分验证,而某些节点不包含。If schema validation errors occur during validation the XmlDocument becomes partially validated with some nodes with correct type information and some without.

  • 验证过程包括检查唯一性和引用约束(xs:IDxs:IDREFxs:keyxs:keyrefxs:unique)。The validation process includes checking for uniqueness and reference constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, and xs:unique).

Validate(ValidationEventHandler, XmlNode)

根据 Schemas 属性中的 XML 架构定义语言 (XSD) 架构,验证指定的 XmlNode 对象。Validates the XmlNode object specified against the XML Schema Definition Language (XSD) schemas in the Schemas property.

public:
 void Validate(System::Xml::Schema::ValidationEventHandler ^ validationEventHandler, System::Xml::XmlNode ^ nodeToValidate);
public void Validate (System.Xml.Schema.ValidationEventHandler validationEventHandler, System.Xml.XmlNode nodeToValidate);
member this.Validate : System.Xml.Schema.ValidationEventHandler * System.Xml.XmlNode -> unit
Public Sub Validate (validationEventHandler As ValidationEventHandler, nodeToValidate As XmlNode)

参数

validationEventHandler
ValidationEventHandler

接收有关架构验证警告和错误的信息的 ValidationEventHandler 对象。The ValidationEventHandler object that receives information about schema validation warnings and errors.

nodeToValidate
XmlNode

XmlDocument 创建的要验证的 XmlNode 对象。The XmlNode object created from an XmlDocument to validate.

例外

XmlNode 对象参数不是从 XmlDocument 创建的。The XmlNode object parameter was not created from an XmlDocument.

XmlNode 对象参数不是元素、特性、文档片段或根节点。The XmlNode object parameter is not an element, attribute, document fragment, or the root node.

发生了架构验证事件并且没有指定任何 ValidationEventHandler 对象。A schema validation event occurred and no ValidationEventHandler object was specified.

示例

有关 Validate 方法的示例,请参阅 Validate 方法。For an example of the Validate method, see the Validate method.

注解

Validate 方法根据 Schemas 属性中包含的架构验证 XmlNode 对象中的 XML 数据。The Validate method validates the XML data in the XmlNode object against the schemas contained in the Schemas property. Validate 方法执行信息集补充。The Validate method performs infoset augmentation. 具体而言,在成功验证后,将应用架构默认值,根据需要将文本值转换为原子值,并将类型信息与已验证的信息项关联。Specifically, 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. 结果是 XmlDocument 中的以前未类型化的 XML 子树替换为类型化的子树。The result is a previously un-typed XML sub-tree in the XmlDocument replaced with a typed sub-tree.

下面是使用 Validate 方法时要考虑的重要注意事项。The following are important notes to consider when using the Validate method.

  • 将忽略 xsi:schemaLocationxsi:noNamespaceSchemaLocation 之类的架构位置提示。Schema location hints like xsi:schemaLocation or xsi:noNamespaceSchemaLocation are ignored.

  • 将忽略内联架构。Inline schemas are ignored.

  • 如果在验证期间发生架构验证错误,则 XmlDocument 将通过某些具有正确类型信息的节点进行部分验证,而某些节点不包含。If schema validation errors occur during validation the XmlDocument becomes partially validated with some nodes with correct type information and some without.

如果要验证的节点是根节点,则验证过程包括检查唯一性和引用约束(xs:IDxs:IDREFxs:keyxs:keyrefxs:unique);否则,将忽略唯一性和引用约束。If the node to validate is the root node, the validation process includes checking for uniqueness and reference constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, and xs:unique); otherwise, uniqueness and reference constraints are omitted.

适用于