System.Xml.Schema.XmlSchemaSet 類別

本文提供此 API 參考文件的補充備註。

重要

  • 請勿使用來自未知或未受信任來源或位置的架構。 這樣做會危害程式代碼的安全性。
  • XML 架構(包括內嵌架構)原本就容易受到阻斷服務攻擊;在未受信任的案例中不接受它們。
  • 架構驗證錯誤訊息和例外狀況可能會公開架構檔案之 con 帳篷模式 l 或 URI 路徑的敏感性資訊。 請小心不要將此資訊公開給不受信任的來電者。
  • 「安全性考慮」一節涵蓋其他安全性考慮。

XmlSchemaSet 是快取或連結庫,您可以在其中儲存 XML 架構定義語言 (XSD) 架構。 XmlSchemaSet 藉由快取記憶體中的架構,而不是從檔案或URL存取架構來改善效能。 每個架構都是透過將架構新增至集合時所指定的命名空間 URI 和位置來識別。 您可以使用 XmlReaderSettings.Schemas 屬性來指派 XmlSchemaSet XML 讀取器應該用於資料驗證的物件。

安全性考量

  • 請勿使用來自未知或未受信任來源的架構。 這樣做會危害程式代碼的安全性。 在包含、匯入和重新定義架構元素中所參考的外部命名空間或位置,會根據包含或匯入這些架構的架構基底 URI 來解析。 例如,如果 包含或匯入架構的基底 URI 是空的 或 null,則會針對目前目錄解析外部位置。 類別 XmlUrlResolver 預設用來解析外部架構。 若要停用架構之 include、import 和 redefine 元素的解析,請將 屬性設定 XmlSchemaSet.XmlResolvernull

  • 類別 XmlSchemaSetSystem.Text.RegularExpressions.Regex 使用 類別來剖析和比對 XML 架構中的正則表示式。 在 XML 架構中使用正規表達式的模式 Facet 驗證可能涉及增加 CPU 使用量,而且應該避免在高可用性案例中。

  • 因使用 XmlSchemaSet 類別而引發的例外狀況,例如 類別 XmlSchemaException 可能包含不應在不受信任的案例中公開的敏感性資訊。 例如, SourceUriXmlSchemaException 屬性會傳回造成例外狀況之架構檔案的 URI 路徑。 屬性 SourceUri 不應該在不受信任的案例中公開。 應正確處理例外狀況,如此一來,此敏感性資訊就不會在不受信任的案例中公開。

範例

下列範例會使用儲存在 XmlSchemaSet 中的結構描述,來驗證 XML 檔案。 XML 檔案中的命名空間 (urn:bookstore-schema),會識別 XmlSchemaSet 中用於驗證的結構描述。 範例的輸出顯示 XML 檔案有兩個架構違規:

  • 第一個 <<book> 元素包含 author> 元素,但沒有<標題>或<價格>元素。

  • 最後<<一本書>元素中的 author> 元素遺漏<了名字>和<姓氏>元素,而是具有無效<的名稱>元素。

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

public class Sample
{
  public static void Main() {

    // Create the XmlSchemaSet class.
    XmlSchemaSet sc = new XmlSchemaSet();

    // Add the schema to the collection.
    sc.Add("urn:bookstore-schema", "books.xsd");

    // Set the validation settings.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas = sc;
    settings.ValidationEventHandler += ValidationCallBack;

    // Create the XmlReader object.
    XmlReader reader = XmlReader.Create("booksSchemaFail.xml", settings);

    // Parse the file.
    while (reader.Read());
  }

  // Display any validation errors.
  private static void ValidationCallBack(object sender, ValidationEventArgs e) {
    Console.WriteLine($"Validation Error:\n   {e.Message}\n");
  }
}
// The example displays output like the following:
//   Validation Error:
//        The element 'book' in namespace 'urn:bookstore-schema' has invalid child element 'author'
//        in namespace 'urn:bookstore-schema'. List of possible elements expected: 'title' in
//        namespace 'urn:bookstore-schema'.
//
//    Validation Error:
//       The element 'author' in namespace 'urn:bookstore-schema' has invalid child element 'name'
//       in namespace 'urn:bookstore-schema'. List of possible elements expected: 'first-name' in
//       namespace 'urn:bookstore-schema'.
Imports System.Xml
Imports System.Xml.Schema
Imports System.IO

Public Module Sample 
  Public Sub Main() 

    ' Create the XmlSchemaSet class.
    Dim sc as XmlSchemaSet = new XmlSchemaSet()

    ' Add the schema to the collection.
    sc.Add("urn:bookstore-schema", "books.xsd")

    ' Set the validation settings.
    Dim settings as XmlReaderSettings = new XmlReaderSettings()
    settings.ValidationType = ValidationType.Schema
    settings.Schemas = sc
    AddHandler settings.ValidationEventHandler, AddressOf ValidationCallBack
 
    ' Create the XmlReader object.
    Dim reader as XmlReader = XmlReader.Create("booksSchemaFail.xml", settings)

    ' Parse the file. 
    While reader.Read()
    End While
    
  End Sub

  ' Display any validation errors.
  Private Sub ValidationCallBack(sender as object, e as ValidationEventArgs) 
    Console.WriteLine($"Validation Error:{vbCrLf}   {e.Message}")
    Console.WriteLine()
  End Sub
End Module
' The example displays output like the following:
'   Validation Error: 
'        The element 'book' in namespace 'urn:bookstore-schema' has invalid child element 'author' 
'        in namespace 'urn:bookstore-schema'. List of possible elements expected: 'title' in 
'        namespace 'urn:bookstore-schema'.
'
'    Validation Error: 
'       The element 'author' in namespace 'urn:bookstore-schema' has invalid child element 'name' 
'       in namespace 'urn:bookstore-schema'. List of possible elements expected: 'first-name' in 
'       namespace 'urn:bookstore-schema'.

輸入

範例會使用下列兩個輸入檔案。

booksSchemaFail.xml:

<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema">
  <book>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
  </book>
  <book genre="novel">
    <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">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

books.xsd:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="urn:bookstore-schema"
    elementFormDefault="qualified"
    targetNamespace="urn:bookstore-schema">

 <xsd:element name="bookstore" type="bookstoreType"/>

 <xsd:complexType name="bookstoreType">
  <xsd:sequence maxOccurs="unbounded">
   <xsd:element name="book"  type="bookType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="bookType">
  <xsd:sequence>
   <xsd:element name="title" type="xsd:string"/>
   <xsd:element name="author" type="authorName"/>
   <xsd:element name="price"  type="xsd:decimal"/>
  </xsd:sequence>
  <xsd:attribute name="genre" type="xsd:string"/>
 </xsd:complexType>

 <xsd:complexType name="authorName">
  <xsd:sequence>
   <xsd:element name="first-name"  type="xsd:string"/>
   <xsd:element name="last-name" type="xsd:string"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>