System.Xml 命名空间

提供基于标准的 XML 处理支持。 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

为文档导航提供和的扩展方法 XmlDocument XmlNodeProvides extension methods for the XmlDocument and XmlNode for document navigation.

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 的选项。Specifies the options for processing DTDs. 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 类型。Represents the XML type for the string. 这允许以特定 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 规范与 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 还为 XML 相关操作提供了其他命名空间。.NET also provides other namespaces for XML-related operations. 有关列表、说明和链接,请参阅 System.Xml 命名空间For a list, descriptions, and links, see System.Xml Namespaces.

异步处理 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 asynchronous programming model. 这些方法可以通过其名称末尾的字符串 "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. 输入流、 XmlTextReaderXmlTextWriter 应该也支持异步操作。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 方法读取块区中的大型文本块。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 的元素 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 实现不满足 "架构组件约束:唯一粒子归属",这在 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.CreateThis 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.

另请参阅