System.Xml Namespace

The System.Xml namespace provides standards-based support for processing 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

表示一个特性。Represents an attribute. 此特性的有效值和默认值在文档类型定义 (DTD) 或架构中进行定义。Valid and default values for the attribute are defined in a document type definition (DTD) or schema.

XmlAttributeCollection

表示可以按名称或索引访问的特性的集合。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 名称进行编码和解码,并提供方法在公共语言运行时类型和 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

Windows Communication Foundation (WCF) 从 XmlReader 中派生以便执行序列化和反序列化的 abstract 类。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

表示实体引用节点。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

提供以下事件的数据:NodeChangedNodeChangingNodeInsertedNodeInsertingNodeRemovedNodeRemovingProvides 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 限定名。Represents an XML qualified name.

XmlReader

表示提供对 XML 数据进行快速、非缓存、只进访问的读取器。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

表示提供对 XML 数据进行快速、非缓存、只进访问的读取器。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

表示提供快速、非缓存、只进方法的写入器,该方法生成包含 XML 数据(这些数据符合 W3C 可扩展标记语言 (XML) 1.0 和“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 数据简化 (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

一个定义必须实现 XML 字典以由 interfaceXmlDictionaryReader 实现使用这一协定的 XmlDictionaryWriterAn 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

提供对一组前缀和命名空间映射的只读访问。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 如何处理实体。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

指定读取器的状态。Specifies the state of the reader.

ValidationType

指定要执行的验证的类型。Specifies the type of validation to perform.

WhitespaceHandling

指定如何处理空白。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

表示处理以下事件的方法:NodeChangedNodeChangingNodeInsertedNodeInsertingNodeRemovedNodeRemovingRepresents 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.AsyncXmlWriterSettings.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在区块中块的方法来读取大型文本。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实现不符合"Schema Component Constraint:元素声明一致,"中所述模型组架构组件约束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 的元素 t2Because 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实现不符合"Schema Component Constraint:唯一粒子归属,"中所述模型组架构组件约束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 或架构,并导入或包含指令。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.