使用 XmlSchemaSet 进行 XML 架构 (XSD) 验证

使用 XML 架构定义语言(XSD)架构可以验证 XmlSchemaSet 的 XML 文档。

验证 XML 文档

XML 文档由 Create 类的方法 XmlReader 进行验证。 若要验证 XML 文档,请构造 XmlReaderSettings 包含 XML 架构定义语言 (XSD) 架构的对象,该语言用于验证 XML 文档。

注释

命名空间 System.Xml.Schema 包含扩展方法,使用 LINQ to XML(C#)LINQ to XML(Visual Basic)时,可以轻松地针对 XSD 文件验证 XML 树。 有关使用 LINQ to XML 验证 XML 文档的详细信息,请参阅如何使用 XSD(LINQ to XML)(C#)如何:使用 XSD 进行验证(LINQ to XML)(Visual Basic)。

将单个架构或一组架构XmlSchemaSet中的任一个作为参数传递给XmlSchemaSet方法Add,可以将其添加到XmlSchemaSet中。 验证文档时,文档的目标命名空间必须与架构集中架构的目标命名空间匹配。

下面是一个 XML 文档示例。

<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 文档的架构。

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

在下面的代码示例中,上述架构将添加到 Schemas 对象的属性 XmlReaderSettings 中。 对象XmlReaderSettings作为参数传递给对象Create的方法XmlReader,该方法验证上述XML文档。

ValidationType 对象的 XmlReaderSettings 属性设置为 Schema,以通过 Create 对象的 XmlReader 方法来强制验证 XML 文档。 ValidationEventHandler被添加到XmlReaderSettings对象中,以处理在 XML 文档和架构验证过程中发现的错误引发的任何WarningError事件。

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

class XmlSchemaSetExample
{
    static void Main()
    {
        XmlReaderSettings booksSettings = new XmlReaderSettings();
        booksSettings.Schemas.Add("http://www.contoso.com/books", "books.xsd");
        booksSettings.ValidationType = ValidationType.Schema;
        booksSettings.ValidationEventHandler += booksSettingsValidationEventHandler;

        XmlReader books = XmlReader.Create("books.xml", booksSettings);

        while (books.Read()) { }
    }

    static void booksSettingsValidationEventHandler(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Warning)
        {
            Console.Write("WARNING: ");
            Console.WriteLine(e.Message);
        }
        else if (e.Severity == XmlSeverityType.Error)
        {
            Console.Write("ERROR: ");
            Console.WriteLine(e.Message);
        }
    }
}
Imports System.Xml
Imports System.Xml.Schema

Class XmlSchemaSetExample

    Shared Sub Main()

        Dim booksSettings As XmlReaderSettings = New XmlReaderSettings()
        booksSettings.Schemas.Add("http://www.contoso.com/books", "books.xsd")
        booksSettings.ValidationType = ValidationType.Schema
        AddHandler booksSettings.ValidationEventHandler, New ValidationEventHandler(AddressOf booksSettingsValidationEventHandler)

        Dim books As XmlReader = XmlReader.Create("books.xml", booksSettings)

        While books.Read()

        End While

    End Sub

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

        If e.Severity = XmlSeverityType.Warning Then
            Console.Write("WARNING: ")
            Console.WriteLine(e.Message)

        ElseIf e.Severity = XmlSeverityType.Error Then
            Console.Write("ERROR: ")
            Console.WriteLine(e.Message)
        End If

    End Sub

End Class

另请参阅