XmlReader XmlReader XmlReader XmlReader Class

定義

表示提供快速、非快取、順向 (Forward-only) 存取 XML 資料的讀取器 (Reader)。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) (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

使用方法來建立XmlReader實例。 CreateUse the Create method to create an XmlReader instance.

XmlReader雖然 .NET Framework 會提供類別的具體執行,例如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:

  • 當您想要從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會擲回 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 架構第一部: 結構和 W3C XML 架構第二部分:資料類型建議)。因此,雖然所有有效 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:key識別xs: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:schemaLocation xsi: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:include XML 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 名稱(例如,專案名稱以數位開頭),就會擲回例外狀況(element)。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.

內容節點包含非空白字元文字、 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.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.

注意

如需開始標記、結束標記和空元素標記的定義,請參閱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 檢查目前的元素是否有 end 元素標記。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 方法和屬性都可用於處理屬性 (Attribute)。Any of the general XmlReader methods and properties can also be used to process attributes. 例如,將 XmlReader 置於屬性 (Attribute) 上之後,NameValue 屬性會反映屬性 (Attribute) 的值。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

這個範例會whileMoveToNextAttribute迴圈中使用方法,以流覽屬性。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 方法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]屬性來傳回系統和公用常值的值。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 資料並傳回值做為 common language runtime (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.

  • Xmlreader.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 架構第二部分所定義的規則: <xref:System.Xml.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. 如需對應資訊,請參閱Config.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.

輸入(雇用日期):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:

  • 預設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. 如果屬性設定為null,即使已設定ProcessInlineSchemaProcessSchemaLocation驗證旗標,也不會解析架構位置。 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您使用衍生自的類別,而且您呼叫了每個專案的LocalNameNamespaceURI Prefix或屬性,則會將傳回的字串加入至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在可能的情況下改用方法; 這些方法不會傳回字串,因此可避免 overfilling 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

在衍生類別中覆寫時,取得指出目前節點是否具有 Value 的值。When 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

取得 XmlReaderSettings 物件,用於建立這個 XmlReader 執行個體。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

取得目前節點的 Common Language Runtime (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)

使用指定的資料流及設定,建立新的 XmlReaderCreates 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,建立新的 XmlReader 執行個體。Creates 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 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。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 的淺層複本 (Shallow Copy)。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 是否與目前的項目相符,然後以要求之型別的形式讀取項目內容。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 是否與目前的項目相符,然後以 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 是否與目前的項目相符,然後以 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 是否與目前的項目相符,然後以 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 是否與目前的項目相符,然後以雙精確度浮點數的形式,讀取目前的項目並傳回內容。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 是否與目前的項目相符,然後以單精確度浮點數的形式,讀取目前的項目並傳回內容。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 是否與目前的項目相符,然後以 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 是否與目前的項目相符,然後以 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 是否與目前的項目相符,然後以 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 是否與目前的項目相符,然後以 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().

適用於

另請參閱