System.Xml Namespace

System.Xml 命名空間提供處理 XML 的標準架構支援。 The System.Xml namespace provides standards-based support for processing XML.

類別

NameTable

實作單一執行緒的 XmlNameTableImplements a single-threaded XmlNameTable.

UniqueId

GUID 的最佳化唯一識別項。A unique identifier optimized for Guids.

XmlAttribute

表示屬性 (Attribute)。Represents an attribute. 屬性的有效和預設值是在文件類型定義 (DTD) 或結構描述中定義。Valid and default values for the attribute are defined in a document type definition (DTD) or schema.

XmlAttributeCollection

表示可用名稱或索引存取的屬性 (Attribute) 集合。Represents a collection of attributes that can be accessed by name or index.

XmlBinaryReaderSession

啟用以動態方式來管理最佳化的字串。Enables optimized strings to be managed in a dynamic way.

XmlBinaryWriterSession

允許使用動態字典來壓縮出現在訊息中的常見字串和維護狀態。Enables using a dynamic dictionary to compress common strings that appear in a message and maintain state.

XmlCDataSection

表示 CDATA 區段。Represents a CDATA section.

XmlCharacterData

提供許多類別使用的文字管理方法。Provides text manipulation methods that are used by several classes.

XmlComment

表示 XML 註解的內容。Represents the content of an XML comment.

XmlConvert

編碼和解碼 XML 名稱,並且提供在 Common Language Runtime 類型和 XML 結構描述定義語言 (XSD) 類型之間轉換的方法。Encodes and decodes XML names, and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. 轉換資料類型時,傳回的值與地區設定無關。When converting data types, the values returned are locale-independent.

XmlDataDocument

允許透過關聯式 DataSet 存放、擷取及管理結構化資料。Allows structured data to be stored, retrieved, and manipulated through a relational DataSet.

XmlDeclaration

代表 XML 宣告節點 <?xml version='1.0'...?>。Represents the XML declaration node <?xml version='1.0'...?>.

XmlDictionary

實作可用來最佳化 Windows Communication Foundation (WCF) 之 XML 讀取器/寫入器實作的字典。Implements a dictionary used to optimize Windows Communication Foundation (WCF)'s XML reader/writer implementations.

XmlDictionaryReader

表示 abstract 類別,這是 Windows Communication Foundation (WCF) 為了要執行序列化和還原序列化而衍生自 XmlReader 的類別。An abstract class that the Windows Communication Foundation (WCF) derives from XmlReader to do serialization and deserialization.

XmlDictionaryReaderQuotas

包含 XmlDictionaryReaders 的可設定配額值。Contains configurable quota values for XmlDictionaryReaders.

XmlDictionaryString

表示儲存在 XmlDictionary 中的項目。Represents an entry stored in a XmlDictionary.

XmlDictionaryWriter

表示抽象類別,這是 Windows Communication Foundation (WCF) 為了要執行序列化和還原序列化而衍生自 XmlWriter 的類別。Represents an abstract class that Windows Communication Foundation (WCF) derives from XmlWriter to do serialization and deserialization.

XmlDocument

表示 XML 文件。Represents an XML document. 您可以於文件中使用這個類別來載入、驗證、編輯、加入和置放 XML。You can use this class to load, validate, edit, add, and position XML in a document.

XmlDocumentFragment

代表適用於樹狀插入作業的輕量型物件。Represents a lightweight object that is useful for tree insert operations.

XmlDocumentType

表示文件類型宣告。Represents the document type declaration.

XmlDocumentXPathExtensions
XmlElement

表示項目。Represents an element.

XmlEntity

代表實體宣告,例如 <!ENTITY... >。Represents an entity declaration, such as <!ENTITY... >.

XmlEntityReference

表示實體 (Entity) 參考節點。Represents an entity reference node.

XmlException

傳回有關上次例外狀況的詳細資訊。Returns detailed information about the last exception.

XmlImplementation

定義一組 XmlDocument 物件的內容。Defines the context for a set of XmlDocument objects.

XmlLinkedNode

取得這個節點的前置或後置節點。Gets the node immediately preceding or following this node.

XmlNamedNodeMap

表示可用名稱或索引存取的節點集合。Represents a collection of nodes that can be accessed by name or index.

XmlNamespaceManager

解析、加入並移除集合的命名空間,並且為這些命名空間提供範圍管理。Resolves, adds, and removes namespaces to a collection and provides scope management for these namespaces.

XmlNameTable

原子化字串物件的資料表。Table of atomized string objects.

XmlNode

表示 XML 文件中的單一節點。Represents a single node in the XML document.

XmlNodeChangedEventArgs

提供 NodeChangedNodeChangingNodeInsertedNodeInsertingNodeRemovedNodeRemoving 事件的資料。Provides data for the NodeChanged, NodeChanging, NodeInserted, NodeInserting, NodeRemoved and NodeRemoving events.

XmlNodeList

表示排序的節點集合。Represents an ordered collection of nodes.

XmlNodeReader

表示讀取器,其提供對 XmlNode 中 XML 資料的快速且非快取順向存取。Represents a reader that provides fast, non-cached forward only access to XML data in an XmlNode.

XmlNotation

代表標記法宣告,例如 <!NOTATION... >。Represents a notation declaration, such as <!NOTATION... >.

XmlParserContext

提供 XmlReader 所需的所有內容資訊以剖析 XML 片段。Provides all the context information required by the XmlReader to parse an XML fragment.

XmlProcessingInstruction

表示處理指示,其中 XML 定義將處理器特定資訊保存在文件的文字中。Represents a processing instruction, which XML defines to keep processor-specific information in the text of the document.

XmlQualifiedName

表示 XML 限定名稱 (Qualified Name)。Represents an XML qualified name.

XmlReader

表示提供快速、非快取、順向 (Forward-only) 存取 XML 資料的讀取器 (Reader)。Represents a reader that provides fast, noncached, forward-only access to XML data.

XmlReaderSettings

指定要在由 XmlReader 方法建立的 Create 物件上支援的一組功能。Specifies a set of features to support on the XmlReader object created by the Create method.

XmlResolver

解析由統一資源識別元 (URI) 所命名的外部 XML 資源。Resolves external XML resources named by a Uniform Resource Identifier (URI).

XmlSecureResolver

以包裝 XmlResolver 物件,並限制基礎 XmlResolver 所能存取的資源,來協助保護其他 XmlResolver 實作的安全性。Helps to secure another implementation of XmlResolver by wrapping the XmlResolver object and restricting the resources that the underlying XmlResolver has access to.

XmlSignificantWhitespace

表示混合內容節點中標記間的空白區,或 xml:space= 'preserve' 範圍內的空白區。Represents white space between markup in a mixed content node or white space within an xml:space= 'preserve' scope. 這個也可以稱為顯著的空白。This is also referred to as significant white space.

XmlText

表示項目或屬性的文字內容。Represents the text content of an element or attribute.

XmlTextReader

表示提供快速、非快取、順向 (Forward-only) 存取 XML 資料的讀取器 (Reader)。Represents a reader that provides fast, non-cached, forward-only access to XML data.

從 .NET Framework 2.0 開始,建議您改用 XmlReader 類別。Starting with the .NET Framework 2.0, we recommend that you use the XmlReader class instead.

XmlTextWriter

表示提供產生資料流或檔案的快速、非快取、順向方法的寫入器,這些資料流或檔案中包含符合 W3C Extensible Markup Language (XML) 1.0 與 XML Recommendation 中命名空間的 XML 資料。Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.

從 .NET Framework 2.0 開始,建議您改用 XmlWriter 類別。Starting with the .NET Framework 2.0, we recommend that you use the XmlWriter class instead.

XmlUrlResolver

解析由統一資源識別元 (URI) 所命名的外部 XML 資源。Resolves external XML resources named by a Uniform Resource Identifier (URI).

XmlValidatingReader

表示讀取器,其提供文件類型定義 (DTD)、XML-Data Reduced (XDR) 結構描述,以及 XML 結構描述定義語言 (XSD) 驗證。Represents a reader that provides document type definition (DTD), XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) validation.

這個類別已經過時。This class is obsolete. 從 .NET Framework 2.0 開始,我們建議使用 XmlReaderSettings 類別及 Create 方法,來建立驗證 XML 讀取器。Starting with the .NET Framework 2.0, we recommend that you use the XmlReaderSettings class and the Create method to create a validating XML reader.

XmlWhitespace

表示項目內容中的空白。Represents white space in element content.

XmlWriter

表示寫入器,其可提供快速、非快取的順向方法來產生含有 XML 資料之資料流或檔案。Represents a writer that provides a fast, non-cached, forward-only way to generate streams or files that contain XML data.

XmlWriterSettings

指定要在由 XmlWriter 方法建立的 Create 物件上支援的一組功能。Specifies a set of features to support on the XmlWriter object created by the Create method.

XmlXapResolver

XmlXapResolver 類型是用來解析 Silverlight 應用程式 XAP 套件中的資源。The XmlXapResolver type is used to resolve resources in the Silverlight application's XAP package.

介面

IApplicationResourceStreamResolver

表示應用程式資源資料流解析程式。Represents an application resource stream resolver.

IFragmentCapableXmlDictionaryWriter

包含在經由 XmlDictionaryWriter 實作之後即可用來處理 XML 片段的屬性和方法。Contains properties and methods that when implemented by a XmlDictionaryWriter, allows processing of XML fragments.

IHasXmlNode

讓類別從目前的內容或位置傳回 XmlNodeEnables a class to return an XmlNode from the current context or position.

IStreamProvider

表示可由類別提供資料流實作的介面。Represents an interface that can be implemented by classes providing streams.

IXmlBinaryReaderInitializer

提供用來重新初始化二進位讀取器的方法,以便讀取新文件。Provides methods for reinitializing a binary reader to read a new document.

IXmlBinaryWriterInitializer

指定衍生自此介面之 XML 二進位寫入器的實作需求。Specifies implementation requirements for XML binary writers that derive from this interface.

IXmlDictionary

interface,定義 Xml 字典必須實作供 XmlDictionaryReaderXmlDictionaryWriter 實作 (Implementation) 使用的合約。An interface that defines the contract that an Xml dictionary must implement to be used by XmlDictionaryReader and XmlDictionaryWriter implementations.

IXmlLineInfo

提供讓類別能夠傳回行和位置資訊的介面。Provides an interface to enable a class to return line and position information.

IXmlMtomReaderInitializer

指定衍生自此介面之 XML MTOM 讀取器的實作需求。Specifies implementation requirements for XML MTOM readers that derive from this interface.

IXmlMtomWriterInitializer

在經過 MTOM 寫入器實作之後,這個介面就可以確保 MTOM 寫入器的初始化。When implemented by an MTOM writer, this interface ensures initialization for an MTOM writer.

IXmlNamespaceResolver

提供對一組前置詞和命名空間 (Namespace) 對應的唯讀存取。Provides read-only access to a set of prefix and namespace mappings.

IXmlTextReaderInitializer

指定衍生自此介面之 XML 文字讀取器的實作需求。Specifies implementation requirements for XML text readers that derive from this interface.

IXmlTextWriterInitializer

指定衍生自此介面之 XML 文字寫入器的實作需求。Specifies implementation requirements for XML text writers that derive from this interface.

列舉

ConformanceLevel

指定 XmlReaderXmlWriter 物件所執行的輸入或輸出檢查數量。Specifies the amount of input or output checking that XmlReader and XmlWriter objects perform.

DtdProcessing

指定處理 DTD 的選項。 DtdProcessing 列舉型別是由 XmlReaderSettings 類別所使用。The DtdProcessing enumeration is used by the XmlReaderSettings class.

EntityHandling

指定 XmlTextReaderXmlValidatingReader 如何處理實體 (Entity)。Specifies how the XmlTextReader or XmlValidatingReader handle entities.

Formatting

指定 XmlTextWriter 的格式選項。Specifies formatting options for the XmlTextWriter.

NamespaceHandling

指定是否要移除 XmlWriter 中的重複命名空間宣告。Specifies whether to remove duplicate namespace declarations in the XmlWriter.

NewLineHandling

指定如何處理分行符號。Specifies how to handle line breaks.

ReadState

指定讀取器 (Reader) 的狀態。Specifies the state of the reader.

ValidationType

指定要執行的驗證類型。Specifies the type of validation to perform.

WhitespaceHandling

指定如何處理泛空白字元 (White Space)。Specifies how white space is handled.

WriteState

指定 XmlWriter 的狀態。Specifies the state of the XmlWriter.

XmlDateTimeSerializationMode

指定在字串和 DateTime 之間轉換時如何處理時間值。Specifies how to treat the time value when converting between string and DateTime.

XmlDictionaryReaderQuotaTypes

列舉 XmlDictionaryReaders 的可設定配額值。Enumerates the configurable quota values for XmlDictionaryReaders.

XmlNamespaceScope

定義命名空間範圍。Defines the namespace scope.

XmlNodeChangedAction

指定節點變更的型別。Specifies the type of node change.

XmlNodeOrder

說明節點相較於第二個節點的文件順序。Describes the document order of a node compared to a second node.

XmlNodeType

指定節點的類型。Specifies the type of node.

XmlOutputMethod

指定用於序列化 XmlWriter 輸出的方法。Specifies the method used to serialize the XmlWriter output.

XmlSpace

取得目前的 xml:space 範圍。Specifies the current xml:space scope.

XmlTokenizedType

表示字串的 XML 型別。 這可允許將字串當做特殊 XML 型別來讀取,例如 CDATA 區段型別。This allows the string to be read as a particular XML type, for example a CDATA section type.

委派

OnXmlDictionaryReaderClose

在關閉讀取器時用於回呼方法的 delegatedelegate for a callback method when closing the reader.

XmlNodeChangedEventHandler

表示處理 NodeChangedNodeChangingNodeInsertedNodeInsertingNodeRemovedNodeRemoving 事件的方法。Represents the method that handles NodeChanged, NodeChanging, NodeInserted, NodeInserting, NodeRemoved and NodeRemoving events.

備註

支援的標準Supported standards

System.Xml命名空間支援這些標準:The System.Xml namespace supports these standards:

請參閱章節與 W3C 規格之間的差異所在的 XML 類別與不同的 W3C 建議的兩個案例。See the section Differences from the W3C specs for two cases in which the XML classes differ from the W3C recommendations.

.NET Framework 也提供其他命名空間與 XML 相關的作業。The .NET Framework also provides other namespaces for XML-related operations. 如需清單、 描述和連結,請參閱System.Xml 命名空間網頁。For a list, descriptions, and links, see the System.Xml Namespaces webpage.

以非同步方式處理 XMLProcessing XML asynchronously

System.Xml.XmlReaderSystem.Xml.XmlWriter類別包括數目為基礎的非同步方法。The System.Xml.XmlReader and System.Xml.XmlWriter classes include a number of asynchronous methods that are based on the . 這些方法可以識別由字串"Async"結尾的名稱。These methods can be identified by the string "Async" at the end of their names. 使用這些方法,您可以撰寫非同步程式碼類似於同步的程式碼,而且您可以輕鬆地將您現有的同步程式碼移轉至非同步程式碼。With these methods, you can write asynchronous code that's similar to your synchronous code, and you can migrate your existing synchronous code to asynchronous code easily.

  • 在 應用程式中使用非同步方法沒有明顯的網路資料流的延遲。Use the asynchronous methods in apps where there is significant network stream latency. 避免使用的記憶體資料流或本機檔案資料流讀取/寫入作業的非同步 Api。Avoid using the asynchronous APIs for memory stream or local file stream read/write operations. 輸入資料流中, XmlTextReader,和XmlTextWriter應支援非同步的作業。The input stream, XmlTextReader, and XmlTextWriter should support asynchronous operations as well. 否則,執行緒仍然會被 I/O 作業所封鎖。Otherwise, threads will still be blocked by I/O operations.

  • 我們不建議混合同步和非同步函式呼叫,因為您可能忘了使用await關鍵字或使用其中一個非同步是必要的同步 API。We don't recommend mixing synchronous and asynchronous function calls, because you might forget to use the await keyword or use a synchronous API where an asynchronous one is necessary.

  • 未設定XmlReaderSettings.Async或是XmlWriterSettings.Async旗標設為true如果您不想要使用非同步方法。Do not set the XmlReaderSettings.Async or XmlWriterSettings.Async flag to true if you don't intend to use an asynchronous method.

  • 如果您忘記指定await關鍵字呼叫非同步方法時,結果會不具決定性:您可能會收到您所預期的結果或例外狀況。If you forget to specify the await keyword when you call an asynchronous method, the results are non-deterministic: You might receive the result you expected or an exception.

  • XmlReader物件讀取大型文字節點,它可能會快取只有部分的文字值,並傳回文字節點,因此擷取XmlReader.Value屬性可能會封鎖 I/O 作業。When an XmlReader object is reading a large text node, it might cache only a partial text value and return the text node, so retrieving the XmlReader.Value property might be blocked by an I/O operation. 使用 XmlReader.GetValueAsync方法來取得文字值,在非同步模式中,或使用XmlReader.ReadValueChunkAsync區塊 (chunk) 中的方法,以讀取大型文字區塊。Use the XmlReader.GetValueAsync method to get the text value in asynchronous mode, or use the XmlReader.ReadValueChunkAsync method to read a large text block in chunks.

  • 當您使用XmlWriter物件,請呼叫XmlWriter.FlushAsync方法之前呼叫XmlWriter.Close以避免封鎖 I/O 作業。When you use an XmlWriter object, call the XmlWriter.FlushAsync method before calling XmlWriter.Close to avoid blocking an I/O operation.

與 W3C 規格之間的差異Differences from the W3C specs

在兩種情況會牽涉到模型群組結構描述元件條件約束System.Xml命名空間與 W3C 建議事項。In two cases that involve constraints on model group schema components, the System.Xml namespace differs from the W3C recommendations.

項目宣告中的一致性:Consistency in element declarations:

在某些情況下,當使用替代群組時,System.Xml實作不符合 「 結構描述元件條件約束:元素宣告一致 」、 「 中所述模型群組結構描述元件條件約束在 W3C 規格的章節。In some cases, when substitution groups are used, the System.Xml implementation does not satisfy the "Schema Component Constraint: Element Declarations Consistent," which is described in the Constraints on Model Group Schema Components section of the W3C spec.

例如,下列結構描述包含具有相同名稱的項目,但會使用相同的內容模型和替代群組中的不同類型。For example, the following schema includes elements that have the same name but different types in the same content model, and substitution groups are used. 這應該會造成錯誤,但是 System.Xml 會編譯和驗證該結構描述,而不會有錯誤。This should cause an error, but System.Xml compiles and validates the schema without errors.

<?xml version="1.0" encoding="utf-8" ?>   
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">  

   <xs:element name="e1" type="t1"/>  
   <xs:complexType name="t1"/>  

   <xs:element name="e2" type="t2" substitutionGroup="e1"/>  
      <xs:complexType name="t2">  
         <xs:complexContent>  
            <xs:extension base="t1">  
         </xs:extension>  
      </xs:complexContent>  
   </xs:complexType>  

   <xs:complexType name="t3">  
      <xs:sequence>  
         <xs:element ref="e1"/>  
         <xs:element name="e2" type="xs:int"/>  
      </xs:sequence>  
   </xs:complexType>  
</xs:schema>  

在此結構描述中,型別 t3 包含項目順序。In this schema, type t3 contains a sequence of elements. 因為替代之故,對序列中 e1 項目的參考可能會產生 e1 型別的 t1 項目或是 e2 型別的 t2 項目。Because of the substitution, the reference to element e1 from the sequence can result either in element e1 of type t1 or in element e2 of type t2. 後者的情況下可能會導致兩個序列e2項目,其中有一個是類型t2,另一個是型別的xs:intThe latter case would result in a sequence of two e2 elements, where one is of type t2 and the other is of type xs:int.

唯一物件屬性:Unique particle attribution:

在下列情況中,System.Xml實作不符合 「 結構描述元件條件約束:唯一物件屬性,」 中所述模型群組結構描述元件條件約束在 W3C 規格的章節。Under the following conditions, the System.Xml implementation does not satisfy the "Schema Component Constraint: Unique Particle Attribution," which is described in the Constraints on Model Group Schema Components section of the W3C spec.

  • 群組中的其中一個項目參考其他項目。One of the elements in the group references another element.

  • 參考的項目是替代群組的標頭項目。The referenced element is a head element of a substitution group.

  • 替代群組會包含具有相同名稱做為其中一個項目群組中的項目。The substitution group contains an element that has the same name as one of the elements in the group.

  • 參考替代群組標頭項目和具有相同名稱的項目,因為不固定的替代群組項目之項目的基數 (minOccurs < maxOccurs)。The cardinality of the element that references the substitution group head element and the element with the same name as a substitution group element is not fixed (minOccurs < maxOccurs).

  • 參考替代群組的項目定義在之前替代群組項目同名的項目的定義。The definition of the element that references the substitution group precedes the definition of the element with the same name as a substitution group element.

例如,在內容模型下方的結構描述是模稜兩可的,而且應該會造成編譯錯誤,但是 System.Xml 會編譯該結構描述,而不會有錯誤。For example, in the schema below the content model is ambiguous and should cause a compilation error, but System.Xml compiles the schema without errors.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">  

  <xs:element name="e1" type="xs:int"/>  
  <xs:element name="e2" type="xs:int" substitutionGroup="e1"/>  

  <xs:complexType name="t3">  
    <xs:sequence>  
      <xs:element ref="e1" minOccurs="0" maxOccurs="1"/>  
      <xs:element name="e2" type="xs:int" minOccurs="0" maxOccurs="1"/>  
    </xs:sequence>  
  </xs:complexType>  

  <xs:element name="e3" type="t3"/>  
</xs:schema>  

如果您嘗試驗證下列 XML 程式碼針對上述的結構描述,驗證將會失敗並出現下列訊息:「 項目 'e3' 有無效的子項目 'e2' 」。 和XmlSchemaValidationException會擲回例外狀況。If you try to validate the following XML against the schema above, the validation will fail with the following message: "The element 'e3' has invalid child element 'e2'." and an XmlSchemaValidationException exception will be thrown.

<e3>  
  <e2>1</e2>  
  <e2>2</e2>  
</e3>  

若要解決此問題,您可以交換 XSD 文件中的項目宣告。To work around this problem, you can swap element declarations in the XSD document. 例如:For example:

<xs:sequence>  
  <xs:element ref="e1" minOccurs="0" maxOccurs="1"/>  
  <xs:element name="e2" type="xs:int" minOccurs="0" maxOccurs="1"/>  
</xs:sequence>  

變成:becomes this:

<xs:sequence>  
  <xs:element name="e2" type="xs:int" minOccurs="0" maxOccurs="1"/>  
  <xs:element ref="e1" minOccurs="0" maxOccurs="1"/>  
</xs:sequence>  

以下是問題的另一個範例相同:Here's another example of the same issue:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">  
   <xs:element name="e1" type="xs:string"/>  
   <xs:element name="e2" type="xs:string" substitutionGroup="e1"/>  

   <xs:complexType name="t3">  
      <xs:sequence>  
         <xs:element ref="e1" minOccurs="0" maxOccurs="1"/>  
         <xs:element name="e2" type="xs:int" minOccurs="0" maxOccurs="1"/>  
      </xs:sequence>  
   </xs:complexType>  
   <xs:element name="e3" type="t3"/>  
</xs:schema>  

如果您嘗試驗證下列 XML 程式碼針對上述的結構描述,驗證將會失敗,發生下列例外狀況:「 未處理例外狀況:System.Xml.Schema.XmlSchemaValidationException:'E2' el 項目無效-根據其資料類型的值 'abc' 無效'http://www.w3.org/2001/XMLSchema:int'-字串 'abc' 不是有效的 Int32 值。 」If you try to validate the following XML against the schema above, the validation will fail with the following exception: "Unhandled Exception: System.Xml.Schema.XmlSchemaValidationException: The 'e2' el element is invalid - The value 'abc' is invalid according to its datatype 'http://www.w3.org/2001/XMLSchema:int' - The string 'abc' is not a valid Int32 value."

<e3><e2>abc</e2></e3>  

安全性考量Security considerations

型別和成員System.Xml命名空間依賴.NET 安全性系統The types and members in the System.Xml namespace rely on the .NET security system. 下列各節討論專屬於 XML 技術的安全性問題。The following sections discuss security issues that are specific to XML technologies.

也請注意,當您使用System.Xml類型和成員,如果 XML 包含有潛在的隱私權影響的資料,您需要以尊重使用者隱私權的方式實作您的應用程式。Also note that when you use the System.Xml types and members, if the XML contains data that has potential privacy implications, you need to implement your app in a way that respects your end users' privacy.

外部存取External access

有幾個 XML 技術能夠在處理期間擷取其他文件。Several XML technologies have the ability to retrieve other documents during processing. 例如,文件類型定義 (DTD) 可位於要剖析的文件中。For example, a document type definition (DTD) can reside in the document being parsed. DTD 還可以存在於要剖析之文件所參考的外部文件中。The DTD can also live in an external document that is referenced by the document being parsed. XML 結構描述定義語言 (XSD) 及 XSLT 技術還能夠包含其他檔案的資訊。The XML Schema definition language (XSD) and XSLT technologies also have the ability to include information from other files. 這些外部資源會帶來一些安全性考量。These external resources can present some security concerns. 比方說,您會想要確保只從受信任的網站,您的應用程式會擷取的檔案,並將它擷取檔案不包含惡意資料。For example, you'll want to ensure that your app retrieves files only from trusted sites, and that the file it retrieves doesn't contain malicious data.

XmlUrlResolver類別用來載入 XML 文件以及解析外部資源,例如實體、 Dtd 或結構描述,以及匯入或 include 指示詞。The XmlUrlResolver class is used to load XML documents and to resolve external resources such as entities, DTDs, or schemas, and import or include directives.

您可以覆寫這個類別,並指定XmlResolver若要使用的物件。You can override this class and specify the XmlResolver object to use. 如果您需要開啟不是由您控制或不受信任的資源,請使用 XmlSecureResolver 類別。Use the XmlSecureResolver class if you need to open a resource that you do not control, or that is untrusted. XmlSecureResolver 可包裝 XmlResolver,並可讓您限制基礎 XmlResolver 可存取的資源。The XmlSecureResolver wraps an XmlResolver and allows you to restrict the resources that the underlying XmlResolver has access to.

阻斷服務Denial of service

下列案例較不易受阻斷服務的攻擊,因為 System.Xml 類別會提供保護免受此類攻擊的方法。The following scenarios are considered to be less vulnerable to denial of service attacks because the System.Xml classes provide a means of protection from such attacks.

如果您擔心遭受阻斷服務攻擊,或正在不受信任的環境下工作,不建議您使用下列案例。The following scenarios are not recommended if you are concerned about denial of service attacks, or if you are working in an untrusted environment.

  • DTD 處理。DTD processing.

  • 結構描述處理。Schema processing. 這包括將不受信任的結構描述加入至結構描述集合、編譯不受信任的結構描述,以及使用不受信任的結構描述進行驗證。This includes adding an untrusted schema to the schema collection, compiling an untrusted schema, and validating by using an untrusted schema.

  • XSLT 處理。XSLT processing.

  • 剖析使用者提供之二進位 XML 資料的任意資料流。Parsing any arbitrary stream of user supplied binary XML data.

  • DOM 作業,如查詢、編輯、在文件之間移動子樹狀目錄,以及儲存 DOM 物件。DOM operations such as querying, editing, moving sub-trees between documents, and saving DOM objects.

如果您顧慮阻絕服務問題,或您正在處理不受信任的來源,請勿啟用 DTD 處理。If you are concerned about denial of service issues or if you are dealing with untrusted sources, do not enable DTD processing. 這預設會停用上XmlReader物件的XmlReader.Create方法會建立。This is disabled by default on XmlReader objects that the XmlReader.Create method creates.

注意

根據預設,XmlTextReader 允許 DTD 處理。The XmlTextReader allows DTD processing by default. 請使用 XmlTextReader.DtdProcessing 屬性停用此功能。Use the XmlTextReader.DtdProcessing property to disable this feature.

如果您已啟用 DTD 處理,您可以使用XmlSecureResolver類別,以限制的資源,XmlReader可以存取。If you have DTD processing enabled, you can use the XmlSecureResolver class to restrict the resources that the XmlReader can access. 您也可以設計您的應用程式,讓 XML 處理具有記憶體和時間限制。You can also design your app so that the XML processing is memory and time constrained. 比方說,您可以設定逾時限制在您的 ASP.NET 應用程式。For example, you can configure timeout limits in your ASP.NET app.

處理考量Processing considerations

因為 XML 文件可以包含其他檔案的參考,所以很難判定需要多大的處理能力來剖析 XML 文件。Because XML documents can include references to other files, it is difficult to determine how much processing power is required to parse an XML document. 例如,XML 文件可以包含 DTD。For example, XML documents can include a DTD. 如果 DTD 包含巢狀實體或複雜的內容模型,則剖析文件會花費大量的時間。If the DTD contains nested entities or complex content models, it could take an excessive amount of time to parse the document.

當使用 XmlReader 時,您可以限制文件的大小,該文件可藉由設定 XmlReaderSettings.MaxCharactersInDocument 屬性來加以剖析。When using XmlReader, you can limit the size of the document that can be parsed by setting the XmlReaderSettings.MaxCharactersInDocument property. 您可以藉由設定 XmlReaderSettings.MaxCharactersFromEntities 屬性來限制從擴充實體所產生的字元數目。You can limit the number of characters that result from expanding entities by setting the XmlReaderSettings.MaxCharactersFromEntities property. 如需設定這些屬性的範例,請參閱適當的參考主題。See the appropriate reference topics for examples of setting these properties.

XSD 及 XSLT 技術具有可影響處理效能的其他功能。The XSD and XSLT technologies have additional capabilities that can affect processing performance. 例如,評估很小的文件時,可能會建構需要大量時間進行處理的 XML 結構描述。For example, it is possible to construct an XML schema that requires a substantial amount of time to process when evaluated over a relatively small document. 還可能將指令碼區塊嵌入 XSLT 樣式表中。It is also possible to embed script blocks within an XSLT style sheet. 這兩種情況會造成潛在的安全性威脅,您的應用程式。Both cases pose a potential security threat to your app.

當建立應用程式使用XslCompiledTransform類別,您應該留意下列項目及其含意:When creating an app that uses the XslCompiledTransform class, you should be aware of the following items and their implications:

  • 依預設會停用 XSLT 指令碼。XSLT scripting is disabled by default. 僅當需要指令碼支援且在完全受信任的環境中運作時,才應啟用 XSLT 指令碼。XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment.

  • 依預設會停用 XSLT document() 函式。The XSLT document() function is disabled by default. 如果您啟用 document() 函式,則藉由傳遞 XmlSecureResolver 物件至 XslCompiledTransform.Transform 方法,限制可存取的資源。If you enable the document() function, restrict the resources that can be accessed by passing an XmlSecureResolver object to the XslCompiledTransform.Transform method.

  • 依預設會啟用擴充物件。Extension objects are enabled by default. 如果將包含擴充物件的 XsltArgumentList 物件傳遞給 XslCompiledTransform.Transform 方法,則會使用這些擴充物件。If an XsltArgumentList object that contains extension objects is passed to the XslCompiledTransform.Transform method, the extension objects are used.

  • XSLT 樣式表可以包含其他檔案及內嵌指令碼區塊的參考。XSLT style sheets can include references to other files and embedded script blocks. 居心不良的使用者會利用這一點,藉由提供您資料或樣式表,使您因執行他們而導致系統持續處理,直到電腦資源不足,來進行攻擊。A malicious user can exploit this by supplying you with data or style sheets that, when executed, can cause your system to process until the computer runs low on resources.

  • 在混合的信任環境中執行的 XSLT 應用程式可能會導致詐騙的樣式表。XSLT apps that run in a mixed trust environment can result in style sheet spoofing. 例如,居心不良的使用者可載入含有害樣式表的物件,然後將其傳遞給另一使用者,該使用者隨後會呼叫 XslCompiledTransform.Transform 方法並執行轉換。For example, a malicious user can load an object with a harmful style sheet and hand it off to another user who subsequently calls the XslCompiledTransform.Transform method and executes the transformation.

不啟用指令碼或 document() 函式 (除非樣式表來自信任的來源),不接受來自不受信任來源的 XslCompiledTransform 物件、XSLT 樣式表或 XML 來源資料,可減輕這些安全性問題。These security issues can be mitigated by not enabling scripting or the document() function unless the style sheet comes from a trusted source, and by not accepting XslCompiledTransform objects, XSLT style sheets, or XML source data from an untrusted source.

例外狀況處理Exception handling

較低的層級元件所擲回例外狀況可能會洩露路徑資訊,您不想公開給應用程式。Exceptions thrown by lower level components can disclose path information that you do not want exposed to the app. 您的應用程式必須攔截例外狀況,並適當地處理它們。Your apps must catch exceptions and process them appropriately.