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.Initial例如,属性由XmlReader.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类的具体实现,例如XmlTextReaderXmlNodeReaderXmlValidatingReader类,但建议仅在以下情况下使用专用类: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:

  • 如果要从XmlNode对象中读取 XML DOM 子树,请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. 有关详细信息,请参阅参考页。CreateSee the Create reference page for details.

XmlReaderXmlException引发 on 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 架构或存储在XmlSchemaSet对象(缓存)中的 XSD 架构来验证数据; 这些方案在 " 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:IDREF遇到xs:keyxs:keyref标识xs: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 和架构)以及 XML xs:include架构xs:import中包含的任何或元素。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

默认情况下,由Create方法创建的 XML 读取器满足以下符合性要求: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 字符范围内,由 W3C XML 1.0 建议的2.2 字符部分定义。- 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 名称都有效,如 W3C XML 1.0 建议的2.3 通用语法构造部分所定义。- 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.

非内容ProcessingInstruction节点包括DocumentType CommentSignificantWhitespace、 、和。WhitespaceNon-content nodes include ProcessingInstruction, DocumentType, Comment, Whitespace, and SignificantWhitespace.

内容节点包括非空白文本、 CDATA EntityReference 、和EndEntityContent nodes include non-white space text, CDATA, EntityReference , and EndEntity.
ReadSubtree 读取元素及其所有子级,并将设置为XmlReader ReadState.Initial的新实例。Read 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.ReadSee 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.

备注

有关开始标记、结束标记和空元素标记的定义,请参阅W3C XML 1.0 建议的3.1 节。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 检查当前节点是否为元素并将读取器推进到下一个节点(调用IsStartElement Read后跟)。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在调用之后,节点属性Name(例如、 NamespaceURIPrefix )反映了该属性的属性,而不是该属性所属的元素的属性。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

此示例使用while循环MoveToNextAttribute中的方法在属性中导航。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. XmlReaderCreate方法XmlValidatingReader 、类和类创建的对象将版本、独立和编码项公开为属性。 XmlTextReaderXmlReader 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]属性来返回系统的值和公共文本。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. 返回的值取决于节点类型;有关详细信息,请参阅参考页。ValueThe 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.

类使用W3C XML 架构第2部分定义的规则: XmlReader数据类型建议。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.exception类中的类型支持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. 下面的示例使用hire-date .xsd 文件将元素转换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.

输入(雇用日期:):Input (hireDate.xml):

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

架构(雇用日期):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. 例如,的异步等效项ReadContentAsObject是。 ReadContentAsObjectAsyncFor 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. 默认情况下,对XmlReader Create通过方法创建的对象禁用 DTD 处理。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:

  • 默认ProcessInlineSchema情况ProcessSchemaLocation下,不设置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. 如果将null ProcessInlineSchema属性设置为,则即使设置了和ProcessSchemaLocation验证标志,也不会解析架构位置。 XmlResolverIf 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的类,并LocalName Prefix 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因此避免了 overfilling 集合的问题。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().

适用于

另请参阅