XmlReader XmlReader XmlReader XmlReader Class

定义

表示提供对 XML 数据进行快速、非缓存、只进访问的读取器。Represents a reader that provides fast, noncached, forward-only access to XML data.

public ref class XmlReader abstract : IDisposable
public abstract class XmlReader : IDisposable
type XmlReader = class
    interface IDisposable
Public MustInherit Class XmlReader
Implements IDisposable
继承
XmlReaderXmlReaderXmlReaderXmlReader
派生
实现

示例

下面的代码示例演示如何使用异步 API 来分析 XML。The following example code shows how to use the asynchronous API to parse XML.

async Task TestReader(System.IO.Stream stream)
{
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.Async = true;

    using (XmlReader reader = XmlReader.Create(stream, settings))
    {
        while (await reader.ReadAsync())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    Console.WriteLine("Start Element {0}", reader.Name);
                    break;
                case XmlNodeType.Text:
                    Console.WriteLine("Text Node: {0}",
                             await reader.GetValueAsync());
                    break;
                case XmlNodeType.EndElement:
                    Console.WriteLine("End Element {0}", reader.Name);
                    break;
                default:
                    Console.WriteLine("Other node {0} with value {1}",
                                    reader.NodeType, reader.Value);
                    break;
            }
        }
    }
}
Public Async Function TestReader(stream As System.IO.Stream) As Task
    Dim settings As New XmlReaderSettings()
    settings.Async = True

    Using reader As XmlReader = XmlReader.Create(stream, settings)
        While (Await reader.ReadAsync())
            Select Case (reader.NodeType)
                Case XmlNodeType.Element
                    Console.WriteLine("Start Element {0}", reader.Name)
                Case XmlNodeType.Text
                    Console.WriteLine("Text Node: {0}",
                             Await reader.GetValueAsync())
                Case XmlNodeType.EndElement
                    Console.WriteLine("End Element {0}", reader.Name)
                Case Else
                    Console.WriteLine("Other node {0} with value {1}",
                                    reader.NodeType, reader.Value)
            End Select
        End While
    End Using
End Function

注解

XmlReader 提供对文档或流中的 XML 数据的只进、 只读访问。XmlReader provides forward-only, read-only access to XML data in a document or stream. 此类符合 W3C可扩展标记语言 (XML) 1.0 (第四版)命名空间中 XML 1.0 (第三版)建议。This class conforms to the W3C Extensible Markup Language (XML) 1.0 (fourth edition) and the Namespaces in XML 1.0 (third edition) recommendations.

XmlReader 方法可以遍历 XML 数据并读取节点的内容。XmlReader methods let you move through XML data and read the contents of a node. 类的属性反映的是读取器定位在当前节点的值。ReadState属性值指示的 XML 读取器的当前状态。The properties of the class reflect the value of the current node, which is where the reader is positioned.The ReadState property value indicates the current state of the XML reader. 例如,该属性设置为ReadState.InitialXmlReader.Read方法并ReadState.Closed通过XmlReader.Close方法。For example, the property is set to ReadState.Initial by the XmlReader.Read method and ReadState.Closed by the XmlReader.Close method. XmlReader 此外提供了数据一致性检查并根据 DTD 或架构验证。XmlReader also provides data conformance checks and validation against a DTD or schema.

XmlReader 使用请求模型检索数据。XmlReader uses a pull model to retrieve data. 此模型:This model:

  • 通过自然的、 由上而下的过程优化简化了状态管理。Simplifies state management by a natural, top-down procedural refinement.

  • 支持多个输入的流和分层。Supports multiple input streams and layering.

  • 允许客户端为分析器提供到其中字符串直接写入,并因此可以避免的额外字符串副本的缓冲区。Enables the client to give the parser a buffer into which the string is directly written, and thus avoids the necessity of an extra string copy.

  • 支持有选择地处理。Supports selective processing. 客户端可以跳过的项目并处理那些感兴趣的应用程序。The client can skip items and process those that are of interest to the application. 此外可以设置属性提前以管理 XML 流 (例如规范化) 的处理方式。You can also set properties in advance to manage how the XML stream is processed (for example, normalization).

本节内容:In this section:

创建 XML 读取器 Creating an XML reader
验证 XML 数据 Validating XML data
数据一致性 Data conformance
节点中导航 Navigating through nodes
读取 XML 元素 Reading XML elements
读取 XML 属性 Reading XML attributes
读取 XML 内容 Reading XML content
将转换为 CLR 类型 Converting to CLR types
异步编程 Asynchronous programming
安全注意事项Security considerations

创建 XML 读取器Creating an XML reader

使用Create方法来创建XmlReader实例。Use the Create method to create an XmlReader instance.

虽然.NET Framework 提供的具体实现,但XmlReader类,如XmlTextReaderXmlNodeReader,和XmlValidatingReader类,我们建议仅在这些方案中使用的专用的类:Although the .NET Framework provides concrete implementations of the XmlReader class, such as the XmlTextReader, XmlNodeReader, and the XmlValidatingReader classes, we recommend that you use the specialized classes only in these scenarios:

  • 当你想要读取从 XML DOM 子树XmlNode对象,请使用XmlNodeReader类。When you want to read an XML DOM subtree from an XmlNode object, use the XmlNodeReader class. (但是,此类不支持 DTD 或架构验证。)(However, this class doesn't support DTD or schema validation.)

  • 如果您必须根据请求展开实体,你不想将文本内容规范化,或者不希望默认情况下返回的属性,使用XmlTextReader类。If you must expand entities on request, you don't want your text content normalized, or you don't want default attributes returned, use the XmlTextReader class.

若要指定一组你想要的 XML 读取器上启用的功能,请将传递System.Xml.XmlReaderSettings对象传递给Create方法。To specify the set of features you want to enable on the XML reader, pass an System.Xml.XmlReaderSettings object to the Create method. 可以使用单个System.Xml.XmlReaderSettings要使用的相同功能,创建多个读取器的对象或修改System.Xml.XmlReaderSettings对象创建新的读取器具有一组不同的功能。You can use a single System.Xml.XmlReaderSettings object to create multiple readers with the same functionality, or modify the System.Xml.XmlReaderSettings object to create a new reader with a different set of features. 与现有读取器,可以方便地添加功能。You can also easily add features to an existing reader.

如果不使用System.Xml.XmlReaderSettings对象,则使用默认设置。If you don't use a System.Xml.XmlReaderSettings object, default settings are used. 请参阅Create引用页面了解详细信息。See the Create reference page for details.

XmlReader 引发XmlException的 XML 分析错误。XmlReader throws an XmlException on XML parse errors. 引发异常后,读取器状态不是可预测的。After an exception is thrown, the state of the reader is not predictable. 例如,报告的节点类型可能不同于当前节点的实际节点类型。For example, the reported node type may be different from the actual node type of the current node. 使用ReadState属性检查是否在读取器处于错误状态。Use the ReadState property to check whether the reader is in error state.

验证 XML 数据Validating XML data

若要定义的 XML 文档及其元素关系、 数据类型和内容约束的结构,请使用文档类型定义 (DTD) 或 XML 架构定义语言 (XSD) 架构。To define the structure of an XML document and its element relationships, data types, and content constraints, you use a document type definition (DTD) or XML Schema definition language (XSD) schema. 如果满足定义的所有语法要求,则格式正确 XML 文档被视为W3C XML 1.0 建议An XML document is considered to be well formed if it meets all the syntactical requirements defined by the W3C XML 1.0 Recommendation. 如果它的格式正确并且符合其 DTD 或架构定义的约束,它被视为有效。It's considered valid if it's well formed and also conforms to the constraints defined by its DTD or schema. (请参阅W3C XML 架构第 1 部分:结构W3C XML 架构第 2 部分:数据类型建议。)因此,虽然所有有效的 XML 文档都是格式正确的,但并不是所有格式正确的 XML 文档都是有效的。(See the W3C XML Schema Part 1: Structures and the W3C XML Schema Part 2: Datatypes recommendations.) Therefore, although all valid XML documents are well formed, not all well-formed XML documents are valid.

您可以验证数据针对 DTD,内联 XSD 架构或 XSD 架构存储在XmlSchemaSet对象 (缓存); 上介绍了这些方案Create参考页。You can validate the data against a DTD, an inline XSD Schema, or an XSD Schema stored in an XmlSchemaSet object (a cache); these scenarios are described on the Create reference page. XmlReader 不支持 XML 数据缩减 (XDR) 架构验证。XmlReader doesn't support XML-Data Reduced (XDR) schema validation.

在使用以下设置XmlReaderSettings类,以指定哪种类型的验证,如果有的话,XmlReader实例支持。You use the following settings on the XmlReaderSettings class to specify what type of validation, if any, the XmlReader instance supports.

使用此XmlReaderSettings成员Use this XmlReaderSettings member 若要指定To specify
DtdProcessing 属性DtdProcessing property 是否允许 DTD 处理。Whether to allow DTD processing. 默认设置为不允许 DTD 处理。The default is to disallow DTD processing.
ValidationType 属性ValidationType property 读取器是否应验证数据,以及要执行 (DTD 或架构) 的验证类型。Whether the reader should validate data, and what type of validation to perform (DTD or schema). 默认设置为无数据验证。The default is no data validation.
ValidationEventHandler 事件ValidationEventHandler event 事件处理程序接收的验证事件的相关信息。An event handler for receiving information about validation events. 如果未提供事件处理程序,在出现第一个验证错误时将引发 XmlExceptionIf an event handler is not provided, an XmlException is thrown on the first validation error.
ValidationFlags 属性ValidationFlags property 其他验证选项通过XmlSchemaValidationFlags枚举成员:Additional validation options through the XmlSchemaValidationFlags enumeration members:

- AllowXmlAttributes-允许 XML 特性 (xml:*) 在实例文档,即使它们不在架构中定义中。- AllowXmlAttributes-- Allow XML attributes (xml:*) in instance documents even when they're not defined in the schema. 属性基于其数据类型进行验证。The attributes are validated based on their data type. 请参阅XmlSchemaValidationFlags设置以在特定方案中使用的参考页。See the XmlSchemaValidationFlags reference page for the setting to use in specific scenarios. (默认情况下禁用)。(Disabled by default.)
- ProcessIdentityConstraints -处理标识约束 (xs:IDxs:IDREFxs:keyxs:keyrefxs:unique) 验证过程中遇到。- ProcessIdentityConstraints --Process identity constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, xs:unique) encountered during validation. (默认情况下启用)。(Enabled by default.)
- ProcessSchemaLocation -处理由指定的架构xsi:schemaLocationxsi:noNamespaceSchemaLocation属性。- ProcessSchemaLocation --Process schemas specified by the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attribute. (默认情况下启用)。(Enabled by default.)
- ProcessInlineSchema-在验证过程中处理内联 XML 架构。- ProcessInlineSchema-- Process inline XML Schemas during validation. (默认情况下禁用)。(Disabled by default.)
- ReportValidationWarnings-如果发生验证警告报告事件。- ReportValidationWarnings--Report events if a validation warning occurs. 如果没有验证特定元素或属性时所依据的 DTD 或 XML 架构,通常会发出警告。A warning is typically issued when there is no DTD or XML Schema to validate a particular element or attribute against. ValidationEventHandler 用于通知。The ValidationEventHandler is used for notification. (默认情况下禁用)。(Disabled by default.)
Schemas 用于验证的 XmlSchemaSetThe XmlSchemaSet to use for validation.
XmlResolver 属性XmlResolver property XmlResolver用于解析和访问外部资源。The XmlResolver for resolving and accessing external resources. 这可以包括外部实体,例如 DTD 和架构和任何xs:includexs:importXML 架构中包含的元素。This can include external entities such as DTD and schemas, and any xs:include or xs:import elements contained in the XML Schema. 如果未指定XmlResolver,则XmlReader使用的默认值XmlUrlResolver使用没有用户凭据。If you don't specify an XmlResolver, the XmlReader uses a default XmlUrlResolver with no user credentials.

数据一致性Data conformance

通过创建的 XML 读取器Create方法默认情况下满足以下符合性要求:XML readers that are created by the Create method meet the following compliance requirements by default:

  • 新行和属性值根据 W3C 进行规范化XML 1.0 建议New lines and attribute value are normalized according to the W3C XML 1.0 Recommendation.

  • 自动展开所有实体。All entities are automatically expanded.

  • 即使在不会验证读取器时,总是会添加文档类型定义中声明的默认属性。Default attributes declared in the document type definition are always added even when the reader doesn't validate.

  • 允许的声明映射到正确的 XML 命名空间 URI 的 XML 前缀。Declaration of XML prefix mapped to the correct XML namespace URI is allowed.

  • 在单个的表示法名称NotationType特性声明并NmTokens在单个Enumeration特性声明是不同的。The notation names in a single NotationType attribute declaration and NmTokens in a single Enumeration attribute declaration are distinct.

使用这些XmlReaderSettings属性以指定类型的一致性检查你想要启用:Use these XmlReaderSettings properties to specify the type of conformance checks you want to enable:

使用此XmlReaderSettings属性Use this XmlReaderSettings property 功能To 默认Default
CheckCharacters 属性CheckCharacters property 启用或禁用以下检查:Enable or disable checks for the following:

的由定义字符是合法的 XML 字符的范围内2.2 字符W3C XML 1.0 建议的部分。- Characters are within the range of legal XML characters, as defined by the 2.2 Characters section of the W3C XML 1.0 Recommendation.
的由定义所有 XML 名称都是否有效, 2.3 常用语法构造W3C XML 1.0 建议的部分。- All XML names are valid, as defined by the 2.3 Common Syntactic Constructs section of the W3C XML 1.0 Recommendation.

当此属性设置为true(默认值),XmlException引发异常,如果 XML 文件中包含非法字符或无效的 XML 名称 (例如,元素名称以数字开头)。When this property is set to true (default), an XmlException exception is thrown if the XML file contains illegal characters or invalid XML names (for example, an element name starts with a number).
启用了字符和名称检查。Character and name checking is enabled.

CheckCharacters 设置为 false 会禁用对字符实体引用的字符检查。Setting CheckCharacters to false turns off character checking for character entity references. 如果读取器正在处理文本数据,始终检查 XML 名称是否有效,而不考虑此设置。If the reader is processing text data, it always checks that XML names are valid, regardless of this setting. 注意: 如果存在 DTD,XML 1.0 建议要求文档级别的一致性。Note: The XML 1.0 recommendation requires document-level conformance when a DTD is present. 因此,如果读取器配置为支持ConformanceLevel.Fragment,但是 XML 数据包含文档类型定义 (DTD)XmlException引发。Therefore, if the reader is configured to support ConformanceLevel.Fragment, but the XML data contains a document type definition (DTD), an XmlException is thrown.
ConformanceLevel 属性ConformanceLevel property 选择强制实施的一致性的级别:Choose the level of conformance to enforce:

- Document.- Document. 符合的规则格式正确的 XML 1.0 文档Conforms to the rules for a well-formed XML 1.0 document.
- Fragment.- Fragment. 符合格式正确的文档片段,可以随着变化所消耗的规则外部已分析的实体Conforms to the rules for a well-formed document fragment that can be consumed as an external parsed entity.
- Auto.- Auto. 符合由读取器决定的级别。Conforms to the level decided by the reader.

如果数据不符合规则,XmlException引发异常。If the data isn't in conformance, an XmlException exception is thrown.
Document

当前节点是 XML 读取器当前定位在的 XML 节点。The current node is the XML node on which the XML reader is currently positioned. 所有XmlReader方法执行与此节点及其所有相关的操作XmlReader属性反映了当前节点的值。All XmlReader methods perform operations in relation to this node, and all XmlReader properties reflect the value of the current node.

以下方法轻松导航节点和分析数据。The following methods make it easy to navigate through nodes and parse data.

使用此XmlReaderSettings方法Use this XmlReaderSettings method 功能To
Read 读取的第一个节点,并进一步处理流的一个节点,一次。Read the first node, and advance through the stream one node at a time. 此类调用通常执行内部while循环。Such calls are typically performed inside a while loop.

使用NodeType属性来获取当前节点的类型 (例如,属性、 注释、 元素和等等)。Use the NodeType property to get the type (for example, attribute, comment, element, and so on) of the current node.
Skip 跳过当前节点的子级,将移动到下一个节点。Skip the children of the current node and move to the next node.
MoveToContentMoveToContentAsyncMoveToContent and MoveToContentAsync 跳过非内容节点,将移到下一个内容节点或文件的末尾。Skip non-content nodes and move to the next content node or to the end of the file.

非内容节点包括ProcessingInstructionDocumentTypeCommentWhitespace,和SignificantWhitespaceNon-content nodes include ProcessingInstruction, DocumentType, Comment, Whitespace, and SignificantWhitespace.

内容节点包括非空白文本CDATAEntityReference ,和EndEntityContent nodes include non-white space text, CDATA, EntityReference , and EndEntity.
ReadSubtree 读取元素及其所有子级,并返回一个新XmlReader实例设置为ReadState.InitialRead an element and all its children, and return a new XmlReader instance set to ReadState.Initial.

此方法可用于创建 XML 元素,则周围的边界例如,如果你想要将数据传递给另一个组件进行处理,并且你想要限制的数据量可以访问该组件。This method is useful for creating boundaries around XML elements; for example, if you want to pass data to another component for processing and you want to limit how much of your data the component can access.

请参阅XmlReader.Read一次文本流的一个节点中导航和显示的每个节点类型的示例的参考页。See the XmlReader.Read reference page for an example of navigating through a text stream one node at a time and displaying the type of each node.

以下各节描述如何可以读取特定类型的数据,如元素、 特性和类型化数据。The following sections describe how you can read specific types of data, such as elements, attributes, and typed data.

读取 XML 元素Reading XML elements

下表列出的方法和属性的XmlReader类提供了用于处理元素。The following table lists the methods and properties that the XmlReader class provides for processing elements. XmlReader 置于某个元素上之后,节点属性(例如 Name)将反映元素的值。After the XmlReader is positioned on an element, the node properties, such as Name, reflect the element values. 除了下面所述的成员之外,XmlReader 类的任何常规方法和属性也可以用于处理元素。In addition to the members described below, any of the general methods and properties of the XmlReader class can also be used to process elements. 例如,可以使用 ReadInnerXml 方法读取元素的内容。For example, you can use the ReadInnerXml method to read the contents of an element.

备注

请参阅部分 3.1 W3C XML 1.0 建议有关的开始标记定义,结束标记和空元素标记。See section 3.1 of the W3C XML 1.0 Recommendation for definitions of start tags, end tags, and empty element tags.

使用此XmlReader成员Use this XmlReader member 功能To
IsStartElement 方法IsStartElement method 检查当前节点是开始标记还是空元素标记。Check if the current node is a start tag or an empty element tag.
ReadStartElement 方法ReadStartElement method 检查当前节点是一个元素,并使读取器前进到下一个节点 (调用IsStartElementRead)。Check that the current node is an element and advance the reader to the next node (calls IsStartElement followed by Read).
ReadEndElement 方法ReadEndElement method 检查当前节点为结束标记,并使读取器前进到下一个节点。Check that the current node is an end tag and advance the reader to the next node.
ReadElementString 方法ReadElementString method 读取纯文本元素。Read a text-only element.
ReadToDescendant 方法ReadToDescendant method 使 XML 读取器前进到下一个具有指定的名称的后代 (子) 元素。Advance the XML reader to the next descendant (child) element that has the specified name.
ReadToNextSibling 方法ReadToNextSibling method 使 XML 读取器前进到具有指定的名称的下一个同级元素。Advance the XML reader to the next sibling element that has the specified name.
IsEmptyElement 属性IsEmptyElement property 检查当前元素是否为结束元素标记。Check if the current element has an end element tag. 例如:For example:

- <item num="123"/> (IsEmptyElementtrue。)- <item num="123"/> (IsEmptyElement is true.)
- <item num="123"> </item> (IsEmptyElementfalse,尽管该元素的内容为空。)- <item num="123"> </item> (IsEmptyElement is false, although the element's content is empty.)

读取元素的文本内容的示例,请参阅ReadString方法。For an example of reading the text content of elements, see the ReadString method. 下面的示例使用的处理元素while循环。The following example processes elements by using a while loop.

while (reader.Read()) {
  if (reader.IsStartElement()) {
    if (reader.IsEmptyElement)
      Console.WriteLine("<{0}/>", reader.Name);
    else {
      Console.Write("<{0}> ", reader.Name);
      reader.Read(); // Read the start tag.
      if (reader.IsStartElement())  // Handle nested elements.
        Console.Write("\r\n<{0}>", reader.Name);
      Console.WriteLine(reader.ReadString());  //Read the text content of the element.
    }
  } 
} 
While reader.Read()
  If reader.IsStartElement() Then
    If reader.IsEmptyElement Then
      Console.WriteLine("<{0}/>", reader.Name)
    Else
      Console.Write("<{0}> ", reader.Name)
      reader.Read() ' Read the start tag.
      If reader.IsStartElement() Then ' Handle nested elements.
        Console.Write(vbCr + vbLf + "<{0}>", reader.Name)
      End If
      Console.WriteLine(reader.ReadString()) 'Read the text content of the element.
    End If
  End If
End While

读取 XML 属性Reading XML attributes

XML 属性最常见的元素,但它们还允许在 XML 声明和文档类型节点上。XML attributes are most commonly found on elements, but they're also allowed on XML declaration and document type nodes.

当定位在元素节点上MoveToAttribute方法可以用来通过元素的属性列表。When positioned on an element node, the MoveToAttribute method lets you go through the attribute list of the element. 请注意,之后MoveToAttribute已调用,节点属性如NameNamespaceURI,和Prefix反映该属性的属性,不是该属性的元素的属性属于。Note that after MoveToAttribute has been called, node properties such as Name, NamespaceURI, and Prefix reflect the properties of that attribute, not the properties of the element the attribute belongs to.

XmlReader类提供了这些方法和属性来读取和处理的元素的属性。The XmlReader class provides these methods and properties to read and process attributes on elements.

使用此XmlReader成员Use this XmlReader member 功能To
HasAttributes 属性HasAttributes property 检查当前节点是否有任何属性。Check whether the current node has any attributes.
AttributeCount 属性AttributeCount property 获取当前元素上的属性。Get the number of attributes on the current element.
MoveToFirstAttribute 方法MoveToFirstAttribute method 将移动到的元素中的第一个属性。Move to the first attribute in an element.
MoveToNextAttribute 方法MoveToNextAttribute method 将移动到下一个元素的属性中。Move to the next attribute in an element.
MoveToAttribute 方法MoveToAttribute method 将移动到指定的属性。Move to a specified attribute.
GetAttribute 方法或Item[String, String]属性GetAttribute method or Item[String, String] property 获取指定属性的值。Get the value of a specified attribute.
IsDefault 属性IsDefault property 检查当前节点是否是从 DTD 或架构中定义的默认值生成属性。Check whether the current node is an attribute that was generated from the default value defined in the DTD or schema.
MoveToElement 方法MoveToElement method 将移动到拥有当前属性的元素。Move to the element that owns the current attribute. 此方法用于通过其属性导航后返回到该元素。Use this method to return to an element after navigating through its attributes.
ReadAttributeValue 方法ReadAttributeValue method 属性值分析为一个或多个TextEntityReference,或EndEntity节点。Parse the attribute value into one or more Text, EntityReference, or EndEntity nodes.

任何常规的 XmlReader 方法和属性也可以用于处理属性。Any of the general XmlReader methods and properties can also be used to process attributes. 例如,在 XmlReader 位于某个属性上之后,NameValue 属性将反映该属性的值。For example, after the XmlReader is positioned on an attribute, the Name and Value properties reflect the values of the attribute. 也可以使用任何内容 Read 方法来获取属性的值。You can also use any of the content Read methods to get the value of the attribute.

此示例使用AttributeCount属性来浏览在元素上的所有属性。This example uses the AttributeCount property to navigate through all the attributes on an element.

// Display all attributes.
if (reader.HasAttributes) {
  Console.WriteLine("Attributes of <" + reader.Name + ">");
  for (int i = 0; i < reader.AttributeCount; i++) {
    Console.WriteLine("  {0}", reader[i]);
  }
  // Move the reader back to the element node.
  reader.MoveToElement(); 
}
' Display all attributes.
If reader.HasAttributes Then
  Console.WriteLine("Attributes of <" + reader.Name + ">")
  Dim i As Integer
  For i = 0 To (reader.AttributeCount - 1)
    Console.WriteLine("  {0}", reader(i))
  Next i
  ' Move the reader back to the element node.
  reader.MoveToElement() 
End If

此示例使用MoveToNextAttribute中的方法while循环来导航属性。This example uses the MoveToNextAttribute method in a while loop to navigate through the attributes.

if (reader.HasAttributes) {
  Console.WriteLine("Attributes of <" + reader.Name + ">");
  while (reader.MoveToNextAttribute()) {
    Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
  }
  // Move the reader back to the element node.
  reader.MoveToElement();
}
If reader.HasAttributes Then
  Console.WriteLine("Attributes of <" + reader.Name + ">")
  While reader.MoveToNextAttribute()
    Console.WriteLine(" {0}={1}", reader.Name, reader.Value)
  End While
  ' Move the reader back to the element node.
  reader.MoveToElement()
End If

读取 XML 声明节点的属性Reading attributes on XML declaration nodes

如果 XML 读取器定位在 XML 声明节点,Value属性返回版本、 独立版和编码信息作为单个字符串。When the XML reader is positioned on an XML declaration node, the Value property returns the version, standalone, and encoding information as a single string. XmlReader 创建的对象Create方法,XmlTextReader类,和XmlValidatingReader类公开版本、 独立版和编码项作为属性。XmlReader objects created by the Create method, the XmlTextReader class, and the XmlValidatingReader class expose the version, standalone, and encoding items as attributes.

读取文档类型节点的属性Reading attributes on document type nodes

XML 读取器定位在文档类型节点上时GetAttribute方法和Item[String, String]属性可以用于返回 SYSTEM 和 PUBLIC 文本的值。When the XML reader is positioned on a document type node, the GetAttribute method and Item[String, String] property can be used to return the values for the SYSTEM and PUBLIC literals. 例如,调用 reader.GetAttribute("PUBLIC") 将返回 PUBLIC 值。For example, calling reader.GetAttribute("PUBLIC") returns the PUBLIC value.

读取属性上处理指令节点Reading attributes on processing instruction nodes

XmlReader 位于某个处理指令节点上时,Value 属性将返回整个文本内容。When the XmlReader is positioned on a processing instruction node, the Value property returns the entire text content. 处理指令节点中的项不会被作为属性对待。Items in the processing instruction node aren't treated as attributes. 它们不能使用读取GetAttributeMoveToAttribute方法。They can't be read with the GetAttribute or MoveToAttribute method.

读取 XML 内容Reading XML content

XMLReader 类包括以下成员,从 XML 文件中读取内容并将内容返回为字符串值。The XMLReader class includes the following members that read content from an XML file and return the content as string values. (若要返回的 CLR 类型,请参阅下一节。)(To return CLR types, see the next section.)

使用此XmlReader成员Use this XmlReader member 功能To
Value 属性Value property 获取当前节点的文本内容。Get the text content of the current node. 返回的值取决于节点类型中;请参阅Value引用页面了解详细信息。The value returned depends on the node type; see the Value reference page for details.
ReadString 方法ReadString method 获取作为字符串的元素或文本节点的内容。Get the content of an element or text node as a string. 此方法停止处理指令和注释。This method stops on processing instructions and comments.

此方法如何处理特定节点类型的详细信息,请参阅ReadString参考页。For details on how this method handles specific node types, see the ReadString reference page.
ReadInnerXmlReadInnerXmlAsync 方法ReadInnerXml and ReadInnerXmlAsync methods 获取当前节点,包括标记中,但不包括开始和结束标记的所有内容。Get all the content of the current node, including the markup, but excluding start and end tags. 例如,对于:For example, for:

<node>this<child id="123"/></node>

ReadInnerXml 返回:ReadInnerXml returns:

this<child id="123"/>
ReadOuterXmlReadOuterXmlAsync 方法ReadOuterXml and ReadOuterXmlAsync methods 获取当前节点及其子级,包括标记和开始/结束标记的所有内容。Get all the content of the current node and its children, including markup and start/end tags. 例如,对于:For example, for:

<node>this<child id="123"/></node>

ReadOuterXml 返回:ReadOuterXml returns:

<node>this<child id="123"/></node>

将转换为 CLR 类型Converting to CLR types

可以使用的成员XmlReader类 (在下表中列出) 来读取 XML 数据和返回值,作为公共语言运行时 (CLR) 类型,而不是字符串。You can use the members of the XmlReader class (listed in the following table) to read XML data and return values as common language runtime (CLR) types instead of strings. 这些成员可以是最适合您的编码任务而无需手动分析或转换字符串值的表示形式获取值。These members enable you to get values in the representation that is most appropriate for your coding task without having to manually parse or convert string values.

  • ReadElementContentAs只能在元素节点类型上调用方法。The ReadElementContentAs methods can only be called on element node types. 这些方法不能在包含子元素或混合内容的元素上使用。These methods cannot be used on elements that contain child elements or mixed content. 在调用时,XmlReader 对象读取开始标记,读取元素内容,然后移过结束元素标记。When called, the XmlReader object reads the start tag, reads the element content, and then moves past the end element tag. 将忽略处理指令和注释并展开实体。Processing instructions and comments are ignored and entities are expanded.

  • ReadContentAs方法读取读取器当前位置处的文本内容和 XML 数据不具有任何架构或数据类型信息与之关联,如果将文本内容转换为请求的返回类型。The ReadContentAs methods read the text content at the current reader position, and if the XML data doesn't have any schema or data type information associated with it, convert the text content to the requested return type. 文本、空白、有效空白和 CDATA 节串联在一起。Text, white space, significant white space and CDATA sections are concatenated. 跳过注释和处理指令,而实体引用自动解决。Comments and processing instructions are skipped, and entity references are automatically resolved.

XmlReader类使用的规则由W3C XML 架构第 2 部分:数据类型建议。The XmlReader class uses the rules defined by the W3C XML Schema Part 2: Datatypes recommendation.

使用此XmlReader方法Use this XmlReader method 返回此 CLR 类型To return this CLR type
ReadContentAsBooleanReadElementContentAsBooleanReadContentAsBoolean and ReadElementContentAsBoolean Boolean
ReadContentAsDateTimeReadElementContentAsDateTimeReadContentAsDateTime and ReadElementContentAsDateTime DateTime
ReadContentAsDoubleReadElementContentAsDoubleReadContentAsDouble and ReadElementContentAsDouble Double
ReadContentAsLongReadElementContentAsLongReadContentAsLong and ReadElementContentAsLong Int64
ReadContentAsIntReadElementContentAsIntReadContentAsInt and ReadElementContentAsInt Int32
ReadContentAsStringReadElementContentAsStringReadContentAsString and ReadElementContentAsString String
ReadContentAsReadElementContentAsReadContentAs and ReadElementContentAs 使用指定的类型returnType参数The type you specify with the returnType parameter
ReadContentAsObjectReadElementContentAsObjectReadContentAsObject and ReadElementContentAsObject 最适合的类型,由指定XmlReader.ValueType属性。The most appropriate type, as specified by the XmlReader.ValueType property. 请参阅System.Xml 类中的类型支持映射信息。See Type Support in the System.Xml Classes for mapping information.

如果元素不能轻松地转换为 CLR 类型由于其格式,可以使用架构映射,确保成功转换。If an element can't easily be converted to a CLR type because of its format, you can use a schema mapping to ensure a successful conversion. 以下示例使用一个.xsd 文件将转换hire-date元素xs:date类型,然后使用ReadElementContentAsDateTime方法以返回元素作为DateTime对象。The following example uses an .xsd file to convert the hire-date element to the xs:date type, and then uses the ReadElementContentAsDateTime method to return the element as a DateTime object.

输入 (hireDate.xml):Input (hireDate.xml):

<employee xmlns="urn:empl-hire">
    <ID>12365</ID>
    <hire-date>2003-01-08</hire-date>
    <title>Accountant</title>
</employee>

架构 (hireDate.xsd):Schema (hireDate.xsd):

<?xml version="1.0"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="urn:empl-hire" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="employee">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="ID" type="xs:unsignedShort" />
        <xs:element name="hire-date" type="xs:date" />
        <xs:element name="title" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

代码:Code:

// Create a validating XmlReader object. The schema 
// provides the necessary type information.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add("urn:empl-hire", "hireDate.xsd");
using (XmlReader reader = XmlReader.Create("hireDate.xml", settings)) {

  // Move to the hire-date element.
  reader.MoveToContent();
  reader.ReadToDescendant("hire-date");

  // Return the hire-date as a DateTime object.
  DateTime hireDate = reader.ReadElementContentAsDateTime();
  Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6));
}
' Create a validating XmlReader object. The schema 
' provides the necessary type information.
Dim settings As XmlReaderSettings = New XmlReaderSettings()
settings.ValidationType = ValidationType.Schema
settings.Schemas.Add("urn:empl-hire", "hireDate.xsd")
Using reader As XmlReader = XmlReader.Create("hireDate.xml", settings) 
  ' Move to the hire-date element.
  reader.MoveToContent()
  reader.ReadToDescendant("hire-date")

  ' Return the hire-date as a DateTime object.
  Dim hireDate As DateTime = reader.ReadElementContentAsDateTime()
  Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6))
End Using

输出:Output:

Six Month Review Date:  7/8/2003 12:00:00 AM  

异步编程Asynchronous programming

大多数的XmlReader方法都具有有"Async"它们的方法名称结尾处的异步对应项。Most of the XmlReader methods have asynchronous counterparts that have "Async" at the end of their method names. 例如,异步等效于ReadContentAsObjectReadContentAsObjectAsyncFor example, the asynchronous equivalent of ReadContentAsObject is ReadContentAsObjectAsync.

可以通过异步方法调用使用以下方法:The following methods can be used with asynchronous method calls:

以下各节介绍异步的方法没有异步对应项的使用情况。The following sections describe asynchronous usage for methods that don't have asynchronous counterparts.

ReadStartElement 方法ReadStartElement method

public static async Task ReadStartElementAsync(this XmlReader reader, string localname, string ns)
{
    if (await reader.MoveToContentAsync() != XmlNodeType.Element)
    {
        throw new InvalidOperationException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
    }
    if ((reader.LocalName == localname) && (reader.NamespaceURI == ns))
    {
        await reader.ReadAsync();
    }
    else
    {
        throw new InvalidOperationException("localName or namespace doesn’t match");
    }
}
<Extension()>
Public Async Function ReadStartElementAsync(reader As XmlReader, localname As String, ns As String) As Task
    If (Await reader.MoveToContentAsync() <> XmlNodeType.Element) Then
        Throw New InvalidOperationException(reader.NodeType.ToString() + " is an invalid XmlNodeType")
    End If

    If ((reader.LocalName = localname) And (reader.NamespaceURI = ns)) Then
        Await reader.ReadAsync()
    Else
        Throw New InvalidOperationException("localName or namespace doesn’t match")
    End If
End Function

ReadEndElement 方法ReadEndElement method

public static async Task ReadEndElementAsync(this XmlReader reader)
{
    if (await reader.MoveToContentAsync() != XmlNodeType.EndElement)
    {
        throw new InvalidOperationException();
    }
    await reader.ReadAsync();
}
<Extension()>
Public Async Function ReadEndElementAsync(reader As XmlReader) As task
    If (Await reader.MoveToContentAsync() <> XmlNodeType.EndElement) Then
        Throw New InvalidOperationException()
    End If
    Await reader.ReadAsync()
End Function

ReadToNextSibling 方法ReadToNextSibling method

public static async Task<bool> ReadToNextSiblingAsync(this XmlReader reader, string localName, string namespaceURI)
{
    if (localName == null || localName.Length == 0)
    {
        throw new ArgumentException("localName is empty or null");
    }
    if (namespaceURI == null)
    {
        throw new ArgumentNullException("namespaceURI");
    }

    // atomize local name and namespace
    localName = reader.NameTable.Add(localName);
    namespaceURI = reader.NameTable.Add(namespaceURI);

    // find the next sibling
    XmlNodeType nt;
    do
    {
        await reader.SkipAsync();
        if (reader.ReadState != ReadState.Interactive)
            break;
        nt = reader.NodeType;
        if (nt == XmlNodeType.Element &&
             ((object)localName == (object)reader.LocalName) &&
             ((object)namespaceURI ==(object)reader.NamespaceURI))
        {
            return true;
        }
    } while (nt != XmlNodeType.EndElement && !reader.EOF);
    
    return false;
}
<Extension()>
Public Async Function ReadToNextSiblingAsync(reader As XmlReader, localName As String, namespaceURI As String) As Task(Of Boolean)
    If (localName = Nothing Or localName.Length = 0) Then
        Throw New ArgumentException("localName is empty or null")
    End If

    If (namespaceURI = Nothing) Then
        Throw New ArgumentNullException("namespaceURI")
    End If

    ' atomize local name and namespace
    localName = reader.NameTable.Add(localName)
    namespaceURI = reader.NameTable.Add(namespaceURI)

    ' find the next sibling
    Dim nt As XmlNodeType
    Do

        Await reader.SkipAsync()
        If (reader.ReadState <> ReadState.Interactive) Then
            Exit Do
        End If
        nt = reader.NodeType
        If ((nt = XmlNodeType.Element) And
           ((CObj(localName) = CObj(reader.LocalName))) And
           (CObj(namespaceURI) = CObj(reader.NamespaceURI))) Then
            Return True
        End If
    Loop While (nt <> XmlNodeType.EndElement And (Not reader.EOF))

    Return False

End Function

ReadToFollowing 方法ReadToFollowing method

public static async Task<bool> ReadToFollowingAsync(this XmlReader reader, string localName, string namespaceURI)
{
    if (localName == null || localName.Length == 0)
    {
        throw new ArgumentException("localName is empty or null");
    }
    if (namespaceURI == null)
    {
        throw new ArgumentNullException("namespaceURI");
    }

    // atomize local name and namespace
    localName = reader.NameTable.Add(localName);
    namespaceURI = reader.NameTable.Add(namespaceURI);

    // find element with that name
    while (await reader.ReadAsync())
    {
        if (reader.NodeType == XmlNodeType.Element && ((object)localName == (object)reader.LocalName) && ((object)namespaceURI == (object)reader.NamespaceURI))
        {
            return true;
        }
    }
    return false;
}
<Extension()>
Public Async Function ReadToFollowingAsync(reader As XmlReader, localName As String, namespaceURI As String) As Task(Of Boolean)
    If (localName = Nothing Or localName.Length = 0) Then
        Throw New ArgumentException("localName is empty or null")
    End If

    If (namespaceURI = Nothing) Then
        Throw New ArgumentNullException("namespaceURI")
    End If

    ' atomize local name and namespace
    localName = reader.NameTable.Add(localName)
    namespaceURI = reader.NameTable.Add(namespaceURI)

    ' find element with that name
    While (Await reader.ReadAsync())
        If ((reader.NodeType = XmlNodeType.Element) And
           (CObj(localName) = CObj(reader.LocalName)) And
           (CObj(namespaceURI) = CObj(reader.NamespaceURI))) Then
            Return True
        End If
    End While

    Return False
End Function

ReadToDescendant 方法ReadToDescendant method

public static async Task<bool> ReadToDescendantAsync(this XmlReader reader, string localName, string namespaceURI)
{
    if (localName == null || localName.Length == 0)
    {
        throw new ArgumentException("localName is empty or null");
    }
    if (namespaceURI == null)
    {
        throw new ArgumentNullException("namespaceURI");
    }
    // save the element or root depth
    int parentDepth = reader.Depth;
    if (reader.NodeType != XmlNodeType.Element)
    {
        // adjust the depth if we are on root node
        if (reader.ReadState == ReadState.Initial)
        {
            parentDepth--;
        }
        else
        {
            return false;
        }
    }
    else if (reader.IsEmptyElement)
    {
        return false;
    }

    // atomize local name and namespace
    localName = reader.NameTable.Add(localName);
    namespaceURI = reader.NameTable.Add(namespaceURI);

    // find the descendant
    while (await reader.ReadAsync() && reader.Depth > parentDepth)
    {
        if (reader.NodeType == XmlNodeType.Element && ((object)localName == (object)reader.LocalName) && ((object)namespaceURI == (object)reader.NamespaceURI))
        {
            return true;
        }
    }
    return false;
}
<Extension()>
Public Async Function ReadToDescendantAsync(reader As XmlReader, localName As String, namespaceURI As String) As Task(Of Boolean)
    If (localName = Nothing Or localName.Length = 0) Then
        Throw New ArgumentException("localName is empty or null")
    End If

    If (namespaceURI = Nothing) Then
        Throw New ArgumentNullException("namespaceURI")
    End If

    ' save the element or root depth
    Dim parentDepth As Integer = reader.Depth
    If (reader.NodeType <> XmlNodeType.Element) Then
        ' adjust the depth if we are on root node
        If (reader.ReadState = ReadState.Initial) Then
            parentDepth -= 1
        Else
            Return False
        End If
    ElseIf (reader.IsEmptyElement) Then
        Return False
    End If
    ' atomize local name and namespace
    localName = reader.NameTable.Add(localName)
    namespaceURI = reader.NameTable.Add(namespaceURI)

    ' find the descendant
    While (Await reader.ReadAsync() And reader.Depth > parentDepth)
        If (reader.NodeType = XmlNodeType.Element And
           (CObj(localName) = CObj(reader.LocalName)) And
           (CObj(namespaceURI) = CObj(reader.NamespaceURI))) Then
            Return True
        End If
    End While

    Return False
End Function

安全注意事项Security considerations

使用时,请考虑以下XmlReader类:Consider the following when working with the XmlReader class:

  • 从引发的异常XmlReader可能会泄露冒泡到您的应用程序可能不希望的路径信息。Exceptions thrown from the XmlReader can disclose path information that you might not want bubbled up to your app. 您的应用程序必须捕获异常并进行相应的处理。Your app must catch exceptions and process them appropriately.

  • 不要启用 DTD 处理,如果你担心拒绝服务问题或如果您正在处理不可信的源。Do not enable DTD processing if you're concerned about denial of service issues or if you're dealing with untrusted sources. 默认情况下禁用 DTD 处理XmlReader创建的对象Create方法。DTD processing is disabled by default for XmlReader objects created by the Create method.

    如果启用了 DTD 处理,可以使用 XmlSecureResolver 限制 XmlReader 可以访问的资源。If you have DTD processing enabled, you can use the XmlSecureResolver 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 time-out limits in your ASP.NET app.

  • XML 数据可以包含对外部资源(例如架构文件)的引用。XML data can include references to external resources such as a schema file. 默认情况下,通过解析外部资源XmlUrlResolver使用没有用户凭据的对象。By default, external resources are resolved by using an XmlUrlResolver object with no user credentials. 通过执行下列操作之一,可以使此操作更加安全:You can secure this further by doing one of the following:

  • ProcessInlineSchemaProcessSchemaLocation验证标志XmlReaderSettings对象不默认设置。The ProcessInlineSchema and ProcessSchemaLocation validation flags of an XmlReaderSettings object aren't set by default. 这样,在处理来自不可信的源的 XML 数据时,可以帮助防止 XmlReader 受到基于架构的攻击。This helps to protect the XmlReader against schema-based attacks when it is processing XML data from an untrusted source. 设置了这些标志后,XmlResolver 对象的 XmlReaderSettings 用于在 XmlReader 中解析实例文档中遇到的架构位置。When these flags are set, the XmlResolver of the XmlReaderSettings object is used to resolve schema locations encountered in the instance document in the XmlReader. 如果XmlResolver属性设置为null,架构位置不是解析即使ProcessInlineSchemaProcessSchemaLocation设置验证标志。If the XmlResolver property is set to null, schema locations aren't resolved even if the ProcessInlineSchema and ProcessSchemaLocation validation flags are set.

    在验证过程中添加的架构会添加新类型,并且可能更改被验证的文档的验证结果。Schemas added during validation add new types and can change the validation outcome of the document being validated. 因此,只应从可信的源解析外部架构。As a result, external schemas should only be resolved from trusted sources.

    我们建议禁用ProcessIdentityConstraints标志时验证不可信的大型 XML 文档中的高可用性方案中,针对文档的很大程度上具有标识约束的架构。We recommend disabling the ProcessIdentityConstraints flag when validating untrusted, large XML documents in high availability scenarios against a schema that has identity constraints over a large part of the document. 默认情况下启用此标志。This flag is enabled by default.

  • XML 数据可以包含大量属性、命名空间声明、嵌套元素等,需要大量的时间来处理。XML data can contain a large number of attributes, namespace declarations, nested elements and so on that require a substantial amount of time to process. 将发送到的输入的大小限制XmlReader,你可以:To limit the size of the input that is sent to the XmlReader, you can:

  • ReadValueChunk方法可用于处理大数据的数据流。The ReadValueChunk method can be used to handle large streams of data. 此方法一次读取少量的字符,而不是为整个值分配单个字符串。This method reads a small number of characters at a time instead of allocating a single string for the whole value.

  • 在读取 XML 文档具有大量唯一的本地名称、 命名空间或前缀,则会出现问题。When reading an XML document with a large number of unique local names, namespaces, or prefixes, a problem can occur. 如果您使用的派生的类XmlReader,并调用LocalNamePrefix,或NamespaceURI每个项的属性,则返回的字符串添加到NameTableIf you are using a class that derives from XmlReader, and you call the LocalName, Prefix, or NamespaceURI property for each item, the returned string is added to a NameTable. 包含的集合NameTable绝不会减小大小,创建字符串句柄的虚拟内存泄漏。The collection held by the NameTable never decreases in size, creating a virtual memory leak of the string handles. 有关这一种解决方法是从派生NameTable类,并强制实施最大大小配额。One mitigation for this is to derive from the NameTable class and enforce a maximum size quota. (没有方法来防止利用NameTable,或切换NameTable已满时)。(There is no way to prevent the use of a NameTable, or to switch the NameTable when it is full). 另一种缓解是避免使用提到的属性,并改用MoveToAttribute方法替换IsStartElement方法在可能的情况; 这些方法不返回的字符串和这样可以避免过度填充问题NameTable集合。Another mitigation is to avoid using the properties mentioned and instead use the MoveToAttribute method with the IsStartElement method where possible; those methods don't return strings and thus avoid the problem of overfilling the NameTable collection.

  • XmlReaderSettings 对象可以包含敏感信息,例如用户凭据。XmlReaderSettings objects can contain sensitive information such as user credentials. 不可信的组件可能会使用 XmlReaderSettings 对象及其用户凭据来创建 XmlReader 对象,以读取数据。An untrusted component could use the XmlReaderSettings object and its user credentials to create XmlReader objects to read data. 缓存时要小心XmlReaderSettings对象,或传递时XmlReaderSettings到另一个对象从一个组件。Be careful when caching XmlReaderSettings objects, or when passing the XmlReaderSettings object from one component to another.

  • 不接受来自不可信的源的支持组件,例如 NameTableXmlNamespaceManagerXmlResolver 对象。Do not accept supporting components, such as NameTable, XmlNamespaceManager, and XmlResolver objects, from an untrusted source.

构造函数

XmlReader() XmlReader() XmlReader() XmlReader()

初始化 XmlReader 类的新实例。Initializes a new instance of the XmlReader class.

属性

AttributeCount AttributeCount AttributeCount AttributeCount

当在派生类中被重写时,获取当前节点上的属性数。When overridden in a derived class, gets the number of attributes on the current node.

BaseURI BaseURI BaseURI BaseURI

当在派生类中被重写时,获取当前节点的基 URI。When overridden in a derived class, gets the base URI of the current node.

CanReadBinaryContent CanReadBinaryContent CanReadBinaryContent CanReadBinaryContent

获取一个值,该值指示 XmlReader 是否实现二进制内容读取方法。Gets a value indicating whether the XmlReader implements the binary content read methods.

CanReadValueChunk CanReadValueChunk CanReadValueChunk CanReadValueChunk

获取一个值,该值指示 XmlReader 是否实现 ReadValueChunk(Char[], Int32, Int32) 方法。Gets a value indicating whether the XmlReader implements the ReadValueChunk(Char[], Int32, Int32) method.

CanResolveEntity CanResolveEntity CanResolveEntity CanResolveEntity

获取一个值,该值指示此读取器是否可以分析和解析实体。Gets a value indicating whether this reader can parse and resolve entities.

Depth Depth Depth Depth

当在派生类中被重写时,获取 XML 文档中当前节点的深度。When overridden in a derived class, gets the depth of the current node in the XML document.

EOF EOF EOF EOF

当在派生类中被重写时,获取一个值,该值指示此读取器是否定位在流的结尾。When overridden in a derived class, gets a value indicating whether the reader is positioned at the end of the stream.

HasAttributes HasAttributes HasAttributes HasAttributes

获取一个值,该值指示当前节点是否有任何属性。Gets a value indicating whether the current node has any attributes.

HasValue HasValue HasValue HasValue

当在派生类中被重写时,获取一个值,该值指示当前节点是否可以具有 ValueWhen overridden in a derived class, gets a value indicating whether the current node can have a Value.

IsDefault IsDefault IsDefault IsDefault

当在派生类中被重写时,获取一个值,该值指示当前节点是否是从 DTD 或架构中定义的默认值生成的特性。When overridden in a derived class, gets a value indicating whether the current node is an attribute that was generated from the default value defined in the DTD or schema.

IsEmptyElement IsEmptyElement IsEmptyElement IsEmptyElement

当在派生类中被重写时,获取一个值,该值指示当前节点是否为空元素(例如 <MyElement/>)。When overridden in a derived class, gets a value indicating whether the current node is an empty element (for example, <MyElement/>).

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

当在派生类中被重写时,获取具有指定索引的属性的值。When overridden in a derived class, gets the value of the attribute with the specified index.

Item[String, String] Item[String, String] Item[String, String] Item[String, String]

当在派生类中被重写时,获取具有指定 LocalNameNamespaceURI 的属性的值。When overridden in a derived class, gets the value of the attribute with the specified LocalName and NamespaceURI.

Item[String] Item[String] Item[String] Item[String]

当在派生类中被重写时,获取具有指定 Name 的属性的值。When overridden in a derived class, gets the value of the attribute with the specified Name.

LocalName LocalName LocalName LocalName

当在派生类中被重写时,获取当前节点的本地名称。When overridden in a derived class, gets the local name of the current node.

Name Name Name Name

当在派生类中被重写时,获取当前节点的限定名。When overridden in a derived class, gets the qualified name of the current node.

NamespaceURI NamespaceURI NamespaceURI NamespaceURI

当在派生类中被重写时,获取读取器定位在其上的节点的命名空间 URI(采用 W3C 命名空间规范中定义的形式)。When overridden in a derived class, gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned.

NameTable NameTable NameTable NameTable

当在派生类中被重写时,获取与该实现关联的 XmlNameTableWhen overridden in a derived class, gets the XmlNameTable associated with this implementation.

NodeType NodeType NodeType NodeType

当在派生类中被重写时,获取当前节点的类型。When overridden in a derived class, gets the type of the current node.

Prefix Prefix Prefix Prefix

当在派生类中被重写时,获取与当前节点关联的命名空间前缀。When overridden in a derived class, gets the namespace prefix associated with the current node.

QuoteChar QuoteChar QuoteChar QuoteChar

当在派生类中被重写时,获取用于括住特性节点值的引号字符。When overridden in a derived class, gets the quotation mark character used to enclose the value of an attribute node.

ReadState ReadState ReadState ReadState

当在派生类中被重写时,获取读取器的状态。When overridden in a derived class, gets the state of the reader.

SchemaInfo SchemaInfo SchemaInfo SchemaInfo

获取作为架构验证结果分配给当前节点的架构信息。Gets the schema information that has been assigned to the current node as a result of schema validation.

Settings Settings Settings Settings

获取用于创建此 XmlReader 实例的 XmlReaderSettings 对象。Gets the XmlReaderSettings object used to create this XmlReader instance.

Value Value Value Value

当在派生类中被重写时,获取当前节点的文本值。When overridden in a derived class, gets the text value of the current node.

ValueType ValueType ValueType ValueType

获取当前节点的公共语言运行时 (CLR) 类型。Gets The Common Language Runtime (CLR) type for the current node.

XmlLang XmlLang XmlLang XmlLang

当在派生类中被重写时,获取当前的 xml:lang 范围。When overridden in a derived class, gets the current xml:lang scope.

XmlSpace XmlSpace XmlSpace XmlSpace

当在派生类中被重写时,获取当前的 xml:space 范围。When overridden in a derived class, gets the current xml:space scope.

方法

Close() Close() Close() Close()

当在派生类中被重写时,将 ReadState 更改为 ClosedWhen overridden in a derived class, changes the ReadState to Closed.

Create(Stream) Create(Stream) Create(Stream) Create(Stream)

使用带默认设置的指定流创建新的 XmlReader 实例。Creates a new XmlReader instance using the specified stream with default settings.

Create(Stream, XmlReaderSettings) Create(Stream, XmlReaderSettings) Create(Stream, XmlReaderSettings) Create(Stream, XmlReaderSettings)

使用指定的流和设置创建一个新的 XmlReader 实例。Creates a new XmlReader instance with the specified stream and settings.

Create(Stream, XmlReaderSettings, String) Create(Stream, XmlReaderSettings, String) Create(Stream, XmlReaderSettings, String) Create(Stream, XmlReaderSettings, String)

使用指定的流、基 URI 和设置创建一个新的 XmlReader 实例。Creates a new XmlReader instance using the specified stream, base URI, and settings.

Create(Stream, XmlReaderSettings, XmlParserContext) Create(Stream, XmlReaderSettings, XmlParserContext) Create(Stream, XmlReaderSettings, XmlParserContext) Create(Stream, XmlReaderSettings, XmlParserContext)

使用指定的流、设置和用于分析的上下文信息创建一个新的 XmlReader 实例。Creates a new XmlReader instance using the specified stream, settings, and context information for parsing.

Create(String) Create(String) Create(String) Create(String)

用指定的 URI 创建一个新的 XmlReader 实例。Creates a new XmlReader instance with specified URI.

Create(String, XmlReaderSettings) Create(String, XmlReaderSettings) Create(String, XmlReaderSettings) Create(String, XmlReaderSettings)

使用指定的 URI 和设置创建新的 XmlReader 实例。Creates a new XmlReader instance by using the specified URI and settings.

Create(String, XmlReaderSettings, XmlParserContext) Create(String, XmlReaderSettings, XmlParserContext) Create(String, XmlReaderSettings, XmlParserContext) Create(String, XmlReaderSettings, XmlParserContext)

使用指定的 URI、设置和进行分析的上下文信息创建一个新的 XmlReader 实例。Creates a new XmlReader instance by using the specified URI, settings, and context information for parsing.

Create(TextReader) Create(TextReader) Create(TextReader) Create(TextReader)

使用指定的文本读取器创建一个新的 XmlReader 实例。Creates a new XmlReader instance by using the specified text reader.

Create(TextReader, XmlReaderSettings) Create(TextReader, XmlReaderSettings) Create(TextReader, XmlReaderSettings) Create(TextReader, XmlReaderSettings)

使用指定的文本读取器和设置创建一个新的 XmlReader 实例。Creates a new XmlReader instance by using the specified text reader and settings.

Create(TextReader, XmlReaderSettings, String) Create(TextReader, XmlReaderSettings, String) Create(TextReader, XmlReaderSettings, String) Create(TextReader, XmlReaderSettings, String)

使用指定的文本读取器、设置和基 URI 创建一个新的 XmlReaderCreates a new XmlReader instance by using the specified text reader, settings, and base URI.

Create(TextReader, XmlReaderSettings, XmlParserContext) Create(TextReader, XmlReaderSettings, XmlParserContext) Create(TextReader, XmlReaderSettings, XmlParserContext) Create(TextReader, XmlReaderSettings, XmlParserContext)

使用指定的文本读取器、设置和要用于分析的上下文信息创建一个新的 XmlReader 实例。Creates a new XmlReader instance by using the specified text reader, settings, and context information for parsing.

Create(XmlReader, XmlReaderSettings) Create(XmlReader, XmlReaderSettings) Create(XmlReader, XmlReaderSettings) Create(XmlReader, XmlReaderSettings)

使用指定的 XML 读取器和设置创建一个新的 XmlReader 实例。Creates a new XmlReader instance by using the specified XML reader and settings.

Dispose() Dispose() Dispose() Dispose()

释放 XmlReader 类的当前实例所使用的所有资源。Releases all resources used by the current instance of the XmlReader class.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由 XmlReader 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the XmlReader and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetAttribute(Int32) GetAttribute(Int32) GetAttribute(Int32) GetAttribute(Int32)

当在派生类中被重写时,获取具有指定索引的属性的值。When overridden in a derived class, gets the value of the attribute with the specified index.

GetAttribute(String) GetAttribute(String) GetAttribute(String) GetAttribute(String)

当在派生类中被重写时,获取具有指定 Name 的属性的值。When overridden in a derived class, gets the value of the attribute with the specified Name.

GetAttribute(String, String) GetAttribute(String, String) GetAttribute(String, String) GetAttribute(String, String)

当在派生类中被重写时,获取具有指定 LocalNameNamespaceURI 的属性的值。When overridden in a derived class, gets the value of the attribute with the specified LocalName and NamespaceURI.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
GetValueAsync() GetValueAsync() GetValueAsync() GetValueAsync()

异步获取当前节点的值。Asynchronously gets the value of the current node.

IsName(String) IsName(String) IsName(String) IsName(String)

返回一个值,该值指示字符串参数是否是有效的 XML 名称。Returns a value indicating whether the string argument is a valid XML name.

IsNameToken(String) IsNameToken(String) IsNameToken(String) IsNameToken(String)

返回一个值,该值指示该字符串参数是否是有效的 XML 名称标记。Returns a value indicating whether or not the string argument is a valid XML name token.

IsStartElement() IsStartElement() IsStartElement() IsStartElement()

调用 MoveToContent() 并测试当前内容节点是否是开始标记或空元素标记。Calls MoveToContent() and tests if the current content node is a start tag or empty element tag.

IsStartElement(String) IsStartElement(String) IsStartElement(String) IsStartElement(String)

调用 MoveToContent() 并测试当前内容节点是否是开始标记或空元素标记,以及所找到元素的 Name 属性是否与给定的参数匹配。Calls MoveToContent() and tests if the current content node is a start tag or empty element tag and if the Name property of the element found matches the given argument.

IsStartElement(String, String) IsStartElement(String, String) IsStartElement(String, String) IsStartElement(String, String)

调用 MoveToContent() 并测试当前内容节点是否是开始标记或空元素标记,以及所找到元素的 LocalNameNamespaceURI 属性是否与给定的字符串匹配。Calls MoveToContent() and tests if the current content node is a start tag or empty element tag and if the LocalName and NamespaceURI properties of the element found match the given strings.

LookupNamespace(String) LookupNamespace(String) LookupNamespace(String) LookupNamespace(String)

当在派生类中被重写时,在当前元素的范围内解析命名空间前缀。When overridden in a derived class, resolves a namespace prefix in the current element's scope.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
MoveToAttribute(Int32) MoveToAttribute(Int32) MoveToAttribute(Int32) MoveToAttribute(Int32)

当在派生类中被重写时,移动到具有指定索引的属性。When overridden in a derived class, moves to the attribute with the specified index.

MoveToAttribute(String) MoveToAttribute(String) MoveToAttribute(String) MoveToAttribute(String)

当在派生类中被重写时,移动到具有指定 Name 的属性。When overridden in a derived class, moves to the attribute with the specified Name.

MoveToAttribute(String, String) MoveToAttribute(String, String) MoveToAttribute(String, String) MoveToAttribute(String, String)

当在派生类中被重写时,移动到具有指定的 LocalNameNamespaceURI 的属性。When overridden in a derived class, moves to the attribute with the specified LocalName and NamespaceURI.

MoveToContent() MoveToContent() MoveToContent() MoveToContent()

检查当前节点是否是内容(非空白文本、CDATAElementEndElementEntityReferenceEndEntity)节点。Checks whether the current node is a content (non-white space text, CDATA, Element, EndElement, EntityReference, or EndEntity) node. 如果此节点不是内容节点,则读取器向前跳至下一个内容节点或文件结尾。If the node is not a content node, the reader skips ahead to the next content node or end of file. 它跳过以下类型的节点:ProcessingInstructionDocumentTypeCommentWhitespaceSignificantWhitespaceIt skips over nodes of the following type: ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace.

MoveToContentAsync() MoveToContentAsync() MoveToContentAsync() MoveToContentAsync()

异步检查当前节点是否为内容节点。Asynchronously checks whether the current node is a content node. 如果此节点不是内容节点,则读取器向前跳至下一个内容节点或文件结尾。If the node is not a content node, the reader skips ahead to the next content node or end of file.

MoveToElement() MoveToElement() MoveToElement() MoveToElement()

当在派生类中被重写时,移动到包含当前属性节点的元素。When overridden in a derived class, moves to the element that contains the current attribute node.

MoveToFirstAttribute() MoveToFirstAttribute() MoveToFirstAttribute() MoveToFirstAttribute()

当在派生类中被重写时,移动到第一个属性。When overridden in a derived class, moves to the first attribute.

MoveToNextAttribute() MoveToNextAttribute() MoveToNextAttribute() MoveToNextAttribute()

当在派生类中被重写时,移动到下一个属性。When overridden in a derived class, moves to the next attribute.

Read() Read() Read() Read()

当在派生类中被重写时,从流中读取下一个节点。When overridden in a derived class, reads the next node from the stream.

ReadAsync() ReadAsync() ReadAsync() ReadAsync()

异步读取该流的下一个节点。Asynchronously reads the next node from the stream.

ReadAttributeValue() ReadAttributeValue() ReadAttributeValue() ReadAttributeValue()

当在派生类中被重写时,将属性值解析为一个或多个 TextEntityReferenceEndEntity 节点。When overridden in a derived class, parses the attribute value into one or more Text, EntityReference, or EndEntity nodes.

ReadContentAs(Type, IXmlNamespaceResolver) ReadContentAs(Type, IXmlNamespaceResolver) ReadContentAs(Type, IXmlNamespaceResolver) ReadContentAs(Type, IXmlNamespaceResolver)

将内容作为指定类型的对象读取。Reads the content as an object of the type specified.

ReadContentAsAsync(Type, IXmlNamespaceResolver) ReadContentAsAsync(Type, IXmlNamespaceResolver) ReadContentAsAsync(Type, IXmlNamespaceResolver) ReadContentAsAsync(Type, IXmlNamespaceResolver)

将内容作为指定类型的对象异步读取。Asynchronously reads the content as an object of the type specified.

ReadContentAsBase64(Byte[], Int32, Int32) ReadContentAsBase64(Byte[], Int32, Int32) ReadContentAsBase64(Byte[], Int32, Int32) ReadContentAsBase64(Byte[], Int32, Int32)

读取内容并返回 Base64 解码的二进制字节。Reads the content and returns the Base64 decoded binary bytes.

ReadContentAsBase64Async(Byte[], Int32, Int32) ReadContentAsBase64Async(Byte[], Int32, Int32) ReadContentAsBase64Async(Byte[], Int32, Int32) ReadContentAsBase64Async(Byte[], Int32, Int32)

异步读取内容并返回 Base64 解码的二进制字节。Asynchronously reads the content and returns the Base64 decoded binary bytes.

ReadContentAsBinHex(Byte[], Int32, Int32) ReadContentAsBinHex(Byte[], Int32, Int32) ReadContentAsBinHex(Byte[], Int32, Int32) ReadContentAsBinHex(Byte[], Int32, Int32)

读取内容并返回 BinHex 解码的二进制字节。Reads the content and returns the BinHex decoded binary bytes.

ReadContentAsBinHexAsync(Byte[], Int32, Int32) ReadContentAsBinHexAsync(Byte[], Int32, Int32) ReadContentAsBinHexAsync(Byte[], Int32, Int32) ReadContentAsBinHexAsync(Byte[], Int32, Int32)

异步读取内容并返回 BinHex 解码的二进制字节。Asynchronously reads the content and returns the BinHex decoded binary bytes.

ReadContentAsBoolean() ReadContentAsBoolean() ReadContentAsBoolean() ReadContentAsBoolean()

将当前位置的文本内容作为 Boolean 读取。Reads the text content at the current position as a Boolean.

ReadContentAsDateTime() ReadContentAsDateTime() ReadContentAsDateTime() ReadContentAsDateTime()

将当前位置的文本内容作为 DateTime 对象读取。Reads the text content at the current position as a DateTime object.

ReadContentAsDateTimeOffset() ReadContentAsDateTimeOffset() ReadContentAsDateTimeOffset() ReadContentAsDateTimeOffset()

将当前位置的文本内容作为 DateTimeOffset 对象读取。Reads the text content at the current position as a DateTimeOffset object.

ReadContentAsDecimal() ReadContentAsDecimal() ReadContentAsDecimal() ReadContentAsDecimal()

将当前位置的文本内容作为 Decimal 对象读取。Reads the text content at the current position as a Decimal object.

ReadContentAsDouble() ReadContentAsDouble() ReadContentAsDouble() ReadContentAsDouble()

将当前位置的文本内容作为双精度浮点数读取。Reads the text content at the current position as a double-precision floating-point number.

ReadContentAsFloat() ReadContentAsFloat() ReadContentAsFloat() ReadContentAsFloat()

将当前位置的文本内容作为单精度浮点数读取。Reads the text content at the current position as a single-precision floating point number.

ReadContentAsInt() ReadContentAsInt() ReadContentAsInt() ReadContentAsInt()

将当前位置的文本内容作为 32 位有符号整数读取。Reads the text content at the current position as a 32-bit signed integer.

ReadContentAsLong() ReadContentAsLong() ReadContentAsLong() ReadContentAsLong()

将当前位置的文本内容作为 64 位有符号整数读取。Reads the text content at the current position as a 64-bit signed integer.

ReadContentAsObject() ReadContentAsObject() ReadContentAsObject() ReadContentAsObject()

将当前位置的文本内容作为 Object 读取。Reads the text content at the current position as an Object.

ReadContentAsObjectAsync() ReadContentAsObjectAsync() ReadContentAsObjectAsync() ReadContentAsObjectAsync()

将当前位置的文本内容作为 Object 对象异步读取。Asynchronously reads the text content at the current position as an Object.

ReadContentAsString() ReadContentAsString() ReadContentAsString() ReadContentAsString()

将当前位置的文本内容作为 String 对象读取。Reads the text content at the current position as a String object.

ReadContentAsStringAsync() ReadContentAsStringAsync() ReadContentAsStringAsync() ReadContentAsStringAsync()

将当前位置的文本内容作为 String 对象异步读取。Asynchronously reads the text content at the current position as a String object.

ReadElementContentAs(Type, IXmlNamespaceResolver) ReadElementContentAs(Type, IXmlNamespaceResolver) ReadElementContentAs(Type, IXmlNamespaceResolver) ReadElementContentAs(Type, IXmlNamespaceResolver)

将元素内容作为请求类型读取。Reads the element content as the requested type.

ReadElementContentAs(Type, IXmlNamespaceResolver, String, String) ReadElementContentAs(Type, IXmlNamespaceResolver, String, String) ReadElementContentAs(Type, IXmlNamespaceResolver, String, String) ReadElementContentAs(Type, IXmlNamespaceResolver, String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后将元素内容作为请求类型读取。Checks that the specified local name and namespace URI matches that of the current element, then reads the element content as the requested type.

ReadElementContentAsAsync(Type, IXmlNamespaceResolver) ReadElementContentAsAsync(Type, IXmlNamespaceResolver) ReadElementContentAsAsync(Type, IXmlNamespaceResolver) ReadElementContentAsAsync(Type, IXmlNamespaceResolver)

将元素内容作为请求类型异步读取。Asynchronously reads the element content as the requested type.

ReadElementContentAsBase64(Byte[], Int32, Int32) ReadElementContentAsBase64(Byte[], Int32, Int32) ReadElementContentAsBase64(Byte[], Int32, Int32) ReadElementContentAsBase64(Byte[], Int32, Int32)

读取元素并对 Base64 内容进行解码。Reads the element and decodes the Base64 content.

ReadElementContentAsBase64Async(Byte[], Int32, Int32) ReadElementContentAsBase64Async(Byte[], Int32, Int32) ReadElementContentAsBase64Async(Byte[], Int32, Int32) ReadElementContentAsBase64Async(Byte[], Int32, Int32)

异步读取元素并对 Base64 内容进行解码。Asynchronously reads the element and decodes the Base64 content.

ReadElementContentAsBinHex(Byte[], Int32, Int32) ReadElementContentAsBinHex(Byte[], Int32, Int32) ReadElementContentAsBinHex(Byte[], Int32, Int32) ReadElementContentAsBinHex(Byte[], Int32, Int32)

读取元素并对 BinHex 内容进行解码。Reads the element and decodes the BinHex content.

ReadElementContentAsBinHexAsync(Byte[], Int32, Int32) ReadElementContentAsBinHexAsync(Byte[], Int32, Int32) ReadElementContentAsBinHexAsync(Byte[], Int32, Int32) ReadElementContentAsBinHexAsync(Byte[], Int32, Int32)

异步读取元素并对 BinHex 内容进行解码。Asynchronously reads the element and decodes the BinHex content.

ReadElementContentAsBoolean() ReadElementContentAsBoolean() ReadElementContentAsBoolean() ReadElementContentAsBoolean()

读取当前元素并将内容作为 Boolean 对象返回。Reads the current element and returns the contents as a Boolean object.

ReadElementContentAsBoolean(String, String) ReadElementContentAsBoolean(String, String) ReadElementContentAsBoolean(String, String) ReadElementContentAsBoolean(String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后读取当前元素,并将内容作为 Boolean 对象返回。Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a Boolean object.

ReadElementContentAsDateTime() ReadElementContentAsDateTime() ReadElementContentAsDateTime() ReadElementContentAsDateTime()

读取当前元素并将内容作为 DateTime 对象返回。Reads the current element and returns the contents as a DateTime object.

ReadElementContentAsDateTime(String, String) ReadElementContentAsDateTime(String, String) ReadElementContentAsDateTime(String, String) ReadElementContentAsDateTime(String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后读取当前元素,并将内容作为 DateTime 对象返回。Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a DateTime object.

ReadElementContentAsDecimal() ReadElementContentAsDecimal() ReadElementContentAsDecimal() ReadElementContentAsDecimal()

读取当前元素并将内容作为 Decimal 对象返回。Reads the current element and returns the contents as a Decimal object.

ReadElementContentAsDecimal(String, String) ReadElementContentAsDecimal(String, String) ReadElementContentAsDecimal(String, String) ReadElementContentAsDecimal(String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后读取当前元素,并将内容作为 Decimal 对象返回。Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a Decimal object.

ReadElementContentAsDouble() ReadElementContentAsDouble() ReadElementContentAsDouble() ReadElementContentAsDouble()

读取当前元素并将内容作为双精度浮点数返回。Reads the current element and returns the contents as a double-precision floating-point number.

ReadElementContentAsDouble(String, String) ReadElementContentAsDouble(String, String) ReadElementContentAsDouble(String, String) ReadElementContentAsDouble(String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后读取当前元素,并将内容作为双精度浮点数返回。Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a double-precision floating-point number.

ReadElementContentAsFloat() ReadElementContentAsFloat() ReadElementContentAsFloat() ReadElementContentAsFloat()

读取当前元素并将内容作为单精度浮点数返回。Reads the current element and returns the contents as single-precision floating-point number.

ReadElementContentAsFloat(String, String) ReadElementContentAsFloat(String, String) ReadElementContentAsFloat(String, String) ReadElementContentAsFloat(String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后读取当前元素,并将内容作为单精度浮点数返回。Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a single-precision floating-point number.

ReadElementContentAsInt() ReadElementContentAsInt() ReadElementContentAsInt() ReadElementContentAsInt()

读取当前元素并将内容作为 32 位有符号整数返回。Reads the current element and returns the contents as a 32-bit signed integer.

ReadElementContentAsInt(String, String) ReadElementContentAsInt(String, String) ReadElementContentAsInt(String, String) ReadElementContentAsInt(String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后读取当前元素,并将内容作为 32 位有符号整数返回。Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a 32-bit signed integer.

ReadElementContentAsLong() ReadElementContentAsLong() ReadElementContentAsLong() ReadElementContentAsLong()

读取当前元素并将内容作为 64 位有符号整数返回。Reads the current element and returns the contents as a 64-bit signed integer.

ReadElementContentAsLong(String, String) ReadElementContentAsLong(String, String) ReadElementContentAsLong(String, String) ReadElementContentAsLong(String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后读取当前元素,并将内容作为 64 位有符号整数返回。Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a 64-bit signed integer.

ReadElementContentAsObject() ReadElementContentAsObject() ReadElementContentAsObject() ReadElementContentAsObject()

读取当前元素并将内容作为 Object 返回。Reads the current element and returns the contents as an Object.

ReadElementContentAsObject(String, String) ReadElementContentAsObject(String, String) ReadElementContentAsObject(String, String) ReadElementContentAsObject(String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后读取当前元素,并将内容作为 Object 返回。Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as an Object.

ReadElementContentAsObjectAsync() ReadElementContentAsObjectAsync() ReadElementContentAsObjectAsync() ReadElementContentAsObjectAsync()

异步读取当前元素并将内容作为 Object 返回。Asynchronously reads the current element and returns the contents as an Object.

ReadElementContentAsString() ReadElementContentAsString() ReadElementContentAsString() ReadElementContentAsString()

读取当前元素并将内容作为 String 对象返回。Reads the current element and returns the contents as a String object.

ReadElementContentAsString(String, String) ReadElementContentAsString(String, String) ReadElementContentAsString(String, String) ReadElementContentAsString(String, String)

检查指定的本地名称和命名空间 URI 与当前元素的本地名称和命名空间 URI 是否匹配,然后读取当前元素,并将内容作为 String 对象返回。Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a String object.

ReadElementContentAsStringAsync() ReadElementContentAsStringAsync() ReadElementContentAsStringAsync() ReadElementContentAsStringAsync()

异步读取当前元素并将内容作为 String 对象返回。Asynchronously reads the current element and returns the contents as a String object.

ReadElementString() ReadElementString() ReadElementString() ReadElementString()

读取纯文本元素。Reads a text-only element. 但是,建议改用 ReadElementContentAsString() 方法,因为该方法可以更直接地处理此操作。However, we recommend that you use the ReadElementContentAsString() method instead, because it provides a more straightforward way to handle this operation.

ReadElementString(String) ReadElementString(String) ReadElementString(String) ReadElementString(String)

在读取纯文本元素之前,检查所找到元素的 Name 属性是否与给定的字符串匹配。Checks that the Name property of the element found matches the given string before reading a text-only element. 但是,建议改用 ReadElementContentAsString() 方法,因为该方法可以更直接地处理此操作。However, we recommend that you use the ReadElementContentAsString() method instead, because it provides a more straightforward way to handle this operation.

ReadElementString(String, String) ReadElementString(String, String) ReadElementString(String, String) ReadElementString(String, String)

在读取纯文本元素之前,检查所找到元素的 LocalNameNamespaceURI 属性是否与给定的字符串匹配。Checks that the LocalName and NamespaceURI properties of the element found matches the given strings before reading a text-only element. 但是,建议改用 ReadElementContentAsString(String, String) 方法,因为该方法可以更直接地处理此操作。However, we recommend that you use the ReadElementContentAsString(String, String) method instead, because it provides a more straightforward way to handle this operation.

ReadEndElement() ReadEndElement() ReadEndElement() ReadEndElement()

检查当前内容节点是否为结束标记并将读取器推进到下一个节点。Checks that the current content node is an end tag and advances the reader to the next node.

ReadInnerXml() ReadInnerXml() ReadInnerXml() ReadInnerXml()

当在派生类中被重写时,将所有内容(包括标记)当做字符串读取。When overridden in a derived class, reads all the content, including markup, as a string.

ReadInnerXmlAsync() ReadInnerXmlAsync() ReadInnerXmlAsync() ReadInnerXmlAsync()

异步读取所有内容,包括作为字符串的标记。Asynchronously reads all the content, including markup, as a string.

ReadOuterXml() ReadOuterXml() ReadOuterXml() ReadOuterXml()

当在派生类中被重写时,读取表示该节点和所有它的子级的内容(包括标记)。When overridden in a derived class, reads the content, including markup, representing this node and all its children.

ReadOuterXmlAsync() ReadOuterXmlAsync() ReadOuterXmlAsync() ReadOuterXmlAsync()

异步读取包含该节点和所有它的子级的内容(包括标记)。Asynchronously reads the content, including markup, representing this node and all its children.

ReadStartElement() ReadStartElement() ReadStartElement() ReadStartElement()

检查当前节点是否为元素并将读取器推进到下一个节点。Checks that the current node is an element and advances the reader to the next node.

ReadStartElement(String) ReadStartElement(String) ReadStartElement(String) ReadStartElement(String)

检查当前内容节点是否为具有给定 Name 的元素并将读取器推进到下一个节点。Checks that the current content node is an element with the given Name and advances the reader to the next node.

ReadStartElement(String, String) ReadStartElement(String, String) ReadStartElement(String, String) ReadStartElement(String, String)

检查当前内容节点是否为具有给定 LocalNameNamespaceURI 的元素并将读取器推进到下一个节点。Checks that the current content node is an element with the given LocalName and NamespaceURI and advances the reader to the next node.

ReadString() ReadString() ReadString() ReadString()

当在派生类中被重写时,将元素或文本节点的内容当做字符串读取。When overridden in a derived class, reads the contents of an element or text node as a string. 但是,建议改用 ReadElementContentAsString 方法,因为该方法可以更直接地处理此操作。However, we recommend that you use the ReadElementContentAsString method instead, because it provides a more straightforward way to handle this operation.

ReadSubtree() ReadSubtree() ReadSubtree() ReadSubtree()

返回新的 XmlReader 实例,此实例可用于读取当前节点及其所有子节点。Returns a new XmlReader instance that can be used to read the current node, and all its descendants.

ReadToDescendant(String) ReadToDescendant(String) ReadToDescendant(String) ReadToDescendant(String)

XmlReader 前进到下一个具有指定限定名的子代元素。Advances the XmlReader to the next descendant element with the specified qualified name.

ReadToDescendant(String, String) ReadToDescendant(String, String) ReadToDescendant(String, String) ReadToDescendant(String, String)

XmlReader 前进到下一个具有指定的本地名称和命名空间 URI 的子代元素。Advances the XmlReader to the next descendant element with the specified local name and namespace URI.

ReadToFollowing(String) ReadToFollowing(String) ReadToFollowing(String) ReadToFollowing(String)

一直读取,直到找到具有指定限定名的元素。Reads until an element with the specified qualified name is found.

ReadToFollowing(String, String) ReadToFollowing(String, String) ReadToFollowing(String, String) ReadToFollowing(String, String)

一直读取,直到找到具有指定的本地名称和命名空间 URI 的元素。Reads until an element with the specified local name and namespace URI is found.

ReadToNextSibling(String) ReadToNextSibling(String) ReadToNextSibling(String) ReadToNextSibling(String)

XmlReader 前进到下一个具有指定限定名的同级元素。Advances the XmlReader to the next sibling element with the specified qualified name.

ReadToNextSibling(String, String) ReadToNextSibling(String, String) ReadToNextSibling(String, String) ReadToNextSibling(String, String)

XmlReader 推进到具有指定的本地名称和命名空间 URI 的下一个同级元素。Advances the XmlReader to the next sibling element with the specified local name and namespace URI.

ReadValueChunk(Char[], Int32, Int32) ReadValueChunk(Char[], Int32, Int32) ReadValueChunk(Char[], Int32, Int32) ReadValueChunk(Char[], Int32, Int32)

读取嵌入在 XML 文档中的大量文本流。Reads large streams of text embedded in an XML document.

ReadValueChunkAsync(Char[], Int32, Int32) ReadValueChunkAsync(Char[], Int32, Int32) ReadValueChunkAsync(Char[], Int32, Int32) ReadValueChunkAsync(Char[], Int32, Int32)

异步读取嵌入在 XML 文档中的大量文本流。Asynchronously reads large streams of text embedded in an XML document.

ResolveEntity() ResolveEntity() ResolveEntity() ResolveEntity()

当在派生类中被重写时,解析 EntityReference 节点的实体引用。When overridden in a derived class, resolves the entity reference for EntityReference nodes.

Skip() Skip() Skip() Skip()

跳过当前节点的子级。Skips the children of the current node.

SkipAsync() SkipAsync() SkipAsync() SkipAsync()

异步跳过当前节点的子级。Asynchronously skips the children of the current node.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

显式界面实现

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

有关此成员的说明,请参见 Dispose()For a description of this member, see Dispose().

适用于

另请参阅