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) 1.0 (第四版)Namespaces in XML 1.0 (第三個版本)建議。This class conforms to the W3C Extensible Markup Language (XML) 1.0 (fourth edition) and the Namespaces in XML 1.0 (third edition) recommendations.

XmlReader 方法可讓您透過 XML 資料移動,並讀取節點的內容。XmlReader methods let you move through XML data and read the contents of a node. 此類別的屬性會反映目前的節點,也就是將讀取器置於其中的值。ReadState屬性值表示 XML 讀取器的目前狀態。The properties of the class reflect the value of the current node, which is where the reader is positioned.The ReadState property value indicates the current state of the XML reader. 比方說,此屬性設為ReadState.InitialXmlReader.Read方法並ReadState.ClosedXmlReader.Close方法。For example, the property is set to ReadState.Initial by the XmlReader.Read method and ReadState.Closed by the XmlReader.Close method. XmlReader 也提供的資料一致性檢查和針對 DTD 或結構描述進行驗證。XmlReader also provides data conformance checks and validation against a DTD or schema.

XmlReader 您可以使用提取模型來擷取資料。XmlReader uses a pull model to retrieve data. 此模型中:This model:

  • 狀態管理簡化自然、 上下程序的精緻化。Simplifies state management by a natural, top-down procedural refinement.

  • 支援多個輸入資料流和分層。Supports multiple input streams and layering.

  • 可讓用戶端給予剖析器到其中的字串會直接寫入,並因此會避免額外的字串複本的緩衝區。Enables the client to give the parser a buffer into which the string is directly written, and thus avoids the necessity of an extra string copy.

  • 支援選擇性處理程序。Supports selective processing. 用戶端可以略過項目,並處理這些感興趣的應用程式。The client can skip items and process those that are of interest to the application. 您也可以設定屬性,以管理 XML 資料流 (例如正規化) 的處理方式。You can also set properties in advance to manage how the XML stream is processed (for example, normalization).

本節內容:In this section:

建立 XML 讀取器 Creating an XML reader
驗證 XML 資料 Validating XML data
資料一致性 Data conformance
瀏覽節點 Navigating through nodes
讀取 XML 項目 Reading XML elements
讀取 XML 屬性 Reading XML attributes
讀取 XML 內容 Reading XML content
將轉換成 CLR 類型 Converting to CLR types
非同步程式設計 Asynchronous programming
安全性考量Security considerations

建立 XML 讀取器Creating an XML reader

使用Create方法用來建立XmlReader執行個體。Use the Create method to create an XmlReader instance.

雖然.NET Framework 提供的具體實作XmlReader類別,例如XmlTextReaderXmlNodeReader,和XmlValidatingReader類別,我們建議您只有在這些情況下,使用特定的類別:Although the .NET Framework provides concrete implementations of the XmlReader class, such as the XmlTextReader, XmlNodeReader, and the XmlValidatingReader classes, we recommend that you use the specialized classes only in these scenarios:

  • 當您想要讀取從 XML DOM 樹狀子目錄XmlNode物件,請使用XmlNodeReader類別。When you want to read an XML DOM subtree from an XmlNode object, use the XmlNodeReader class. (不過,此類別不支援 DTD 或結構描述驗證。)(However, this class doesn't support DTD or schema validation.)

  • 如果您必須展開要求的實體,您不想將文字內容正規化,或您不想預設傳回的屬性,請使用XmlTextReader類別。If you must expand entities on request, you don't want your text content normalized, or you don't want default attributes returned, use the XmlTextReader class.

若要指定您想要的 XML 讀取器上啟用的功能集,請傳遞System.Xml.XmlReaderSettings物件至Create方法。To specify the set of features you want to enable on the XML reader, pass an System.Xml.XmlReaderSettings object to the Create method. 您可以使用單一System.Xml.XmlReaderSettings要使用相同的功能,建立多個讀取器的物件,或修改System.Xml.XmlReaderSettings物件來建立新的讀取器與一組不同的功能。You can use a single System.Xml.XmlReaderSettings object to create multiple readers with the same functionality, or modify the System.Xml.XmlReaderSettings object to create a new reader with a different set of features. 此外,您也很容易可以將功能加入至現有讀取器。You can also easily add features to an existing reader.

如果您未使用System.Xml.XmlReaderSettings物件時,會使用預設設定。If you don't use a System.Xml.XmlReaderSettings object, default settings are used. 請參閱Create參考頁面,如需詳細資訊。See the Create reference page for details.

XmlReader 會擲回XmlExceptionxml 剖析錯誤。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 Schema Part 2:資料型別建議。)因此,雖然所有有效 XML 文件的格式都正確,但是並非所有格式正確的 XML 文件都有效。(See the W3C XML Schema Part 1: Structures and the W3C XML Schema Part 2: Datatypes recommendations.) Therefore, although all valid XML documents are well formed, not all well-formed XML documents are valid.

您可以針對驗證資料 DTD 中,內嵌 XSD 結構描述,或 XSD 結構描述儲存在XmlSchemaSet物件 (快取); 將說明這些情況在Create參考頁面。You can validate the data against a DTD, an inline XSD Schema, or an XSD Schema stored in an XmlSchemaSet object (a cache); these scenarios are described on the Create reference page. XmlReader 不支援 XML 資料精簡 (XDR) 結構描述驗證。XmlReader doesn't support XML-Data Reduced (XDR) schema validation.

您可以使用下列設定上XmlReaderSettings類別,以指定哪一種驗證,如果有的話,XmlReader執行個體可支援。You use the following settings on the XmlReaderSettings class to specify what type of validation, if any, the XmlReader instance supports.

使用此XmlReaderSettings成員Use this XmlReaderSettings member 若要指定To specify
DtdProcessing 屬性DtdProcessing property 是否允許 DTD 處理。Whether to allow DTD processing. 預設不允許 DTD 處理。The default is to disallow DTD processing.
ValidationType 屬性ValidationType property 讀取器是否應該驗證資料,以及要執行 (DTD 或結構描述) 的驗證型別。Whether the reader should validate data, and what type of validation to perform (DTD or schema). 預設不進行資料驗證。The default is no data validation.
ValidationEventHandler 事件ValidationEventHandler event 事件處理常式接收驗證事件的相關資訊。An event handler for receiving information about validation events. 如果未提供事件處理常式,會在第一次發生驗證錯誤時擲回 XmlExceptionIf an event handler is not provided, an XmlException is thrown on the first validation error.
ValidationFlags 屬性ValidationFlags property 其他驗證選項,透過XmlSchemaValidationFlags列舉成員:Additional validation options through the XmlSchemaValidationFlags enumeration members:

- AllowXmlAttributes-允許 XML 屬性 (xml:*) 即使未定義結構描述中的執行個體文件中。- AllowXmlAttributes-- Allow XML attributes (xml:*) in instance documents even when they're not defined in the schema. 會根據屬性的資料型別來驗證該屬性。The attributes are validated based on their data type. 請參閱XmlSchemaValidationFlags設定在特定案例中使用的參考頁面。See the XmlSchemaValidationFlags reference page for the setting to use in specific scenarios. (預設為停用。)(Disabled by default.)
- ProcessIdentityConstraints -處理識別條件約束 (xs:IDxs:IDREFxs:keyxs:keyrefxs:unique) 在驗證期間發生。- ProcessIdentityConstraints --Process identity constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, xs:unique) encountered during validation. (依預設啟用)。(Enabled by default.)
- ProcessSchemaLocation -處理所指定的結構描述xsi:schemaLocationxsi:noNamespaceSchemaLocation屬性。- ProcessSchemaLocation --Process schemas specified by the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attribute. (依預設啟用)。(Enabled by default.)
- ProcessInlineSchema-處理驗證期間的內嵌 XML 結構描述。- ProcessInlineSchema-- Process inline XML Schemas during validation. (預設為停用。)(Disabled by default.)
- ReportValidationWarnings-如果發生驗證警告時,報告事件。- ReportValidationWarnings--Report events if a validation warning occurs. 在沒有可以用於驗證特定項目或屬性的 DTD 或 XML 結構描述時,通常會發出警告。A warning is typically issued when there is no DTD or XML Schema to validate a particular element or attribute against. 會使用 ValidationEventHandler 來進行通知。The ValidationEventHandler is used for notification. (預設為停用。)(Disabled by default.)
Schemas 用來驗證的 XmlSchemaSetThe XmlSchemaSet to use for validation.
XmlResolver 屬性XmlResolver property XmlResolver解析及存取外部資源。The XmlResolver for resolving and accessing external resources. 這可以包括外部實體,例如 DTD 和結構描述,以及任何xs:includexs:importXML 結構描述中包含的項目。This can include external entities such as DTD and schemas, and any xs:include or xs:import elements contained in the XML Schema. 如果您未指定XmlResolver,則XmlReader使用的預設值XmlUrlResolver與不具使用者認證。If you don't specify an XmlResolver, the XmlReader uses a default XmlUrlResolver with no user credentials.

資料一致性Data conformance

所建立的 XML 讀取器Create方法符合下列的合規性需求的預設值:XML readers that are created by the Create method meet the following compliance requirements by default:

  • 新行和屬性值根據正規化 W3C XML 1.0 建議事項New lines and attribute value are normalized according to the W3C XML 1.0 Recommendation.

  • 會自動展開所有實體。All entities are automatically expanded.

  • 即使在不會驗證讀取器時,會固定加入文件類型定義中宣告的預設屬性。Default attributes declared in the document type definition are always added even when the reader doesn't validate.

  • 允許宣告對應至正確的 XML 命名空間 URI 的 XML 前置詞。Declaration of XML prefix mapped to the correct XML namespace URI is allowed.

  • 在單一標記法名稱NotationType屬性宣告並NmTokens在單一Enumeration屬性宣告就會不同。The notation names in a single NotationType attribute declaration and NmTokens in a single Enumeration attribute declaration are distinct.

使用這些XmlReaderSettings屬性,以指定的一致性類型檢查您想要啟用:Use these XmlReaderSettings properties to specify the type of conformance checks you want to enable:

使用此XmlReaderSettings屬性Use this XmlReaderSettings property To 預設Default
CheckCharacters 屬性CheckCharacters property 啟用或停用檢查下列項目:Enable or disable checks for the following:

字元是合法的 XML 字元的範圍內所定義2.2 字元W3C XML 1.0 建議事項一節。- Characters are within the range of legal XML characters, as defined by the 2.2 Characters section of the W3C XML 1.0 Recommendation.
-所有的 XML 名稱是否有效,如同2.3 Common Syntactic Constructs W3C XML 1.0 建議事項一節。- All XML names are valid, as defined by the 2.3 Common Syntactic Constructs section of the W3C XML 1.0 Recommendation.

當這個屬性設定為true(預設)、XmlException擲回例外狀況是 XML 檔案包含不合法的字元或無效的 XML 名稱 (例如,項目名稱以數字開頭)。When this property is set to true (default), an XmlException exception is thrown if the XML file contains illegal characters or invalid XML names (for example, an element name starts with a number).
字元且名稱檢查已啟用。Character and name checking is enabled.

CheckCharacters 設為 false 會關閉字元實體參考的字元檢查。Setting CheckCharacters to false turns off character checking for character entity references. 如果讀取器處理文字資料,它會始終檢查 XML 名稱是否有效,而不論此設定。If the reader is processing text data, it always checks that XML names are valid, regardless of this setting. 注意: 存在 DTD 時,XML 1.0 版建議事項會要求文件層級的一致性。Note: The XML 1.0 recommendation requires document-level conformance when a DTD is present. 因此,如果讀取器設定為支援ConformanceLevel.Fragment,但 XML 資料包含文件類型定義 (DTD),XmlException就會擲回。Therefore, if the reader is configured to support ConformanceLevel.Fragment, but the XML data contains a document type definition (DTD), an XmlException is thrown.
ConformanceLevel 屬性ConformanceLevel property 選擇強制執行的一致性層級:Choose the level of conformance to enforce:

- Document.- Document. 符合的規則語式正確的 XML 1.0 文件Conforms to the rules for a well-formed XML 1.0 document.
- Fragment.- Fragment. 符合格式正確的文件片段做為可使用的規則外部剖析實體Conforms to the rules for a well-formed document fragment that can be consumed as an external parsed entity.
- Auto.- Auto. 符合層級讀取器所決定。Conforms to the level decided by the reader.

如果資料不一致,XmlException擲回例外狀況。If the data isn't in conformance, an XmlException exception is thrown.
Document

目前節點是 XML 讀取器目前所在的 XML 節點。The current node is the XML node on which the XML reader is currently positioned. 所有XmlReader方法會執行與這個節點及其所有相關的作業XmlReader屬性會反映目前節點的值。All XmlReader methods perform operations in relation to this node, and all XmlReader properties reflect the value of the current node.

下列方法讓您輕鬆瀏覽節點和剖析資料。The following methods make it easy to navigate through nodes and parse data.

使用此XmlReaderSettings方法Use this XmlReaderSettings method To
Read 讀取的第一個節點,並一次前進透過資料流的一個節點。Read the first node, and advance through the stream one node at a time. 這類呼叫通常會執行內while迴圈。Such calls are typically performed inside a while loop.

使用NodeType屬性來取得目前節點的類型 (例如屬性、 註解、 項目,等等)。Use the NodeType property to get the type (for example, attribute, comment, element, and so on) of the current node.
Skip 略過目前節點的子系,並移至下一個節點。Skip the children of the current node and move to the next node.
MoveToContentMoveToContentAsyncMoveToContent and MoveToContentAsync 略過非內容節點,並移至下一個內容節點或檔案結尾。Skip non-content nodes and move to the next content node or to the end of the file.

非內容節點包含ProcessingInstructionDocumentTypeCommentWhitespace,和SignificantWhitespaceNon-content nodes include ProcessingInstruction, DocumentType, Comment, Whitespace, and SignificantWhitespace.

內容節點包括非泛空白字元文字CDATAEntityReference ,和EndEntityContent nodes include non-white space text, CDATA, EntityReference , and EndEntity.
ReadSubtree 讀取項目和其所有子系,並傳回新XmlReader設為執行個體ReadState.InitialRead an element and all its children, and return a new XmlReader instance set to ReadState.Initial.

這個方法可用於建立 XML 項目; 周圍的界限例如,如果您想要將資料傳遞至另一個元件進行處理,而且您想要限制您的資料中有多少可以存取元件。This method is useful for creating boundaries around XML elements; for example, if you want to pass data to another component for processing and you want to limit how much of your data the component can access.

請參閱XmlReader.Read參考頁面巡覽的文字資料流的一個節點,一次,並顯示每個節點類型的範例。See the XmlReader.Read reference page for an example of navigating through a text stream one node at a time and displaying the type of each node.

下列各節說明您可以讀取特定類型的資料,例如元素、 屬性的方式,並具型別資料。The following sections describe how you can read specific types of data, such as elements, attributes, and typed data.

讀取 XML 項目Reading XML elements

下表列出的方法和屬性,XmlReader類別提供用於處理項目。The following table lists the methods and properties that the XmlReader class provides for processing elements. XmlReader 定位於項目上後,節點屬性 (如 Name) 就會反映項目值。After the XmlReader is positioned on an element, the node properties, such as Name, reflect the element values. 除了下面說明的成員之外,還可以使用 XmlReader 類別的任意一般方法及屬性來處理項目。In addition to the members described below, any of the general methods and properties of the XmlReader class can also be used to process elements. 例如,您可以使用 ReadInnerXml 方法讀取項目的內容。For example, you can use the ReadInnerXml method to read the contents of an element.

注意

請參閱第 3.1 節W3C XML 1.0 建議事項定義的開始標記、 結束標記與空項目標記。See section 3.1 of the W3C XML 1.0 Recommendation for definitions of start tags, end tags, and empty element tags.

使用此XmlReader成員Use this XmlReader member To
IsStartElement 方法IsStartElement method 檢查目前節點是否開始標記或空白項目標記。Check if the current node is a start tag or an empty element tag.
ReadStartElement 方法ReadStartElement method 檢查目前節點是項目,並使讀取器前進至下一個節點 (呼叫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已呼叫節點屬性這類NameNamespaceURI,和Prefix反映該屬性的屬性、 所屬的項目屬性的屬性。Note that after MoveToAttribute has been called, node properties such as Name, NamespaceURI, and Prefix reflect the properties of that attribute, not the properties of the element the attribute belongs to.

XmlReader類別會提供這些方法和屬性來讀取和處理項目上的屬性。The XmlReader class provides these methods and properties to read and process attributes on elements.

使用此XmlReader成員Use this XmlReader member To
HasAttributes 屬性HasAttributes property 檢查目前節點是否具有任何屬性。Check whether the current node has any attributes.
AttributeCount 屬性AttributeCount property 取得目前的項目屬性的數目。Get the number of attributes on the current element.
MoveToFirstAttribute 方法MoveToFirstAttribute method 移動項目中的第一個屬性。Move to the first attribute in an element.
MoveToNextAttribute 方法MoveToNextAttribute method 移至下一個屬性的項目。Move to the next attribute in an element.
MoveToAttribute 方法MoveToAttribute method 移至指定的屬性。Move to a specified attribute.
GetAttribute 方法或Item[String, String]屬性GetAttribute method or Item[String, String] property 取得指定之屬性的值。Get the value of a specified attribute.
IsDefault 屬性IsDefault property 檢查目前節點是否為 DTD 或結構描述中定義的預設值所產生的屬性。Check whether the current node is an attribute that was generated from the default value defined in the DTD or schema.
MoveToElement 方法MoveToElement method 移至擁有目前屬性的項目。Move to the element that owns the current attribute. 使用這個方法傳回的項目之後瀏覽其屬性。Use this method to return to an element after navigating through its attributes.
ReadAttributeValue 方法ReadAttributeValue method 將屬性值剖析成一或多個TextEntityReference,或EndEntity節點。Parse the attribute value into one or more Text, EntityReference, or EndEntity nodes.

任何一般 XmlReader 方法和屬性都可用於處理屬性 (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

這個範例會使用MoveToNextAttribute方法中的while迴圈來瀏覽屬性。This example uses the MoveToNextAttribute method in a while loop to navigate through the attributes.

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

讀取 XML 宣告節點上的屬性Reading attributes on XML declaration nodes

XML 讀取器必須置於 XML 宣告節點Value屬性會傳回版本、 獨立及編碼資訊,以單一字串。When the XML reader is positioned on an XML declaration node, the Value property returns the version, standalone, and encoding information as a single string. XmlReader 所建立的物件Create方法中,XmlTextReader類別,而XmlValidatingReader類別公開版本、 獨立及編碼項目,做為屬性。XmlReader objects created by the Create method, the XmlTextReader class, and the XmlValidatingReader class expose the version, standalone, and encoding items as attributes.

讀取文件類型節點上的屬性Reading attributes on document type nodes

XML 讀取器必須置於文件類型節點GetAttribute方法和Item[String, String]屬性可以用來傳回 SYSTEM 及 PUBLIC 常值的值。When the XML reader is positioned on a document type node, the GetAttribute method and Item[String, String] property can be used to return the values for the SYSTEM and PUBLIC literals. 例如,呼叫 reader.GetAttribute("PUBLIC") 會傳回 PUBLIC 值。For example, calling reader.GetAttribute("PUBLIC") returns the PUBLIC value.

讀取在處理指示節點上的屬性Reading attributes on processing instruction nodes

XmlReader 置於處理指示節點時,Value 屬性會傳回全部文字內容。When the XmlReader is positioned on a processing instruction node, the Value property returns the entire text content. 處理指示節點中的項目不被視為屬性。Items in the processing instruction node aren't treated as attributes. 無法與閱讀GetAttributeMoveToAttribute方法。They can't be read with the GetAttribute or MoveToAttribute method.

讀取 XML 內容Reading XML content

XMLReader 類別包含下列成員,可從 XML 檔案讀取內容,然後將內容傳回為字串值。The XMLReader class includes the following members that read content from an XML file and return the content as string values. (若要傳回 CLR 型別,請參閱下一節。)(To return CLR types, see the next section.)

使用此XmlReader成員Use this XmlReader member To
Value 屬性Value property 取得目前節點的文字內容。Get the text content of the current node. 傳回的值取決於節點類型;請參閱Value參考頁面,如需詳細資訊。The value returned depends on the node type; see the Value reference page for details.
ReadString 方法ReadString method 取得做為字串的項目或文字節點的內容。Get the content of an element or text node as a string. 此方法會停止處理指示和註解。This method stops on processing instructions and comments.

如需這個方法的特定節點類型的處理方式的詳細資訊,請參閱ReadString參考頁面。For details on how this method handles specific node types, see the ReadString reference page.
ReadInnerXmlReadInnerXmlAsync 方法ReadInnerXml and ReadInnerXmlAsync methods 取得目前的節點,包括標記,但不含開始和結束標記的所有內容。Get all the content of the current node, including the markup, but excluding start and end tags. 例如,若為:For example, for:

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

ReadInnerXml 會傳回:ReadInnerXml returns:

this<child id="123"/>
ReadOuterXmlReadOuterXmlAsync 方法ReadOuterXml and ReadOuterXmlAsync methods 取得目前的節點及其子系,包括標記和開始/結束標記的所有內容。Get all the content of the current node and its children, including markup and start/end tags. 例如,若為:For example, for:

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

ReadOuterXml 會傳回:ReadOuterXml returns:

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

將轉換成 CLR 類型Converting to CLR types

您可以使用的成員XmlReader(下表所列) 的類別讀取 XML 資料,並傳回值,做為通用語言執行平台 (CLR) 型別,而不是字串。You can use the members of the XmlReader class (listed in the following table) to read XML data and return values as common language runtime (CLR) types instead of strings. 這些成員可讓您取得值,而不必手動剖析,或將字串值轉換為最適合您的程式碼撰寫工作的表示法。These members enable you to get values in the representation that is most appropriate for your coding task without having to manually parse or convert string values.

  • ReadElementContentAs只有元素節點型別上呼叫方法。The ReadElementContentAs methods can only be called on element node types. 這些方法無法用於包含項目子系或混合內容的項目。These methods cannot be used on elements that contain child elements or mixed content. 呼叫後,XmlReader 物件會讀取開始標記、讀取項目內容,然後移動到超過結尾項目標記以後的部分。When called, the XmlReader object reads the start tag, reads the element content, and then moves past the end element tag. 處理指示及註解會略過,並且實體會展開。Processing instructions and comments are ignored and entities are expanded.

  • ReadContentAs方法讀取的文字內容,目前的讀取器位置,和 XML 資料不需要任何結構描述或資料型別與其建立關聯的資訊時,將文字內容轉換成要求的傳回型別。The ReadContentAs methods read the text content at the current reader position, and if the XML data doesn't have any schema or data type information associated with it, convert the text content to the requested return type. 文字、泛空白字元、顯著泛空白字元及 CDATA 區段都是串連的。Text, white space, significant white space and CDATA sections are concatenated. 註解和處理指示會略過,並會自動解析實體參考。Comments and processing instructions are skipped, and entity references are automatically resolved.

XmlReader類別會使用所定義的規則W3C XML 結構描述第 2 部分:資料型別建議。The XmlReader class uses the rules defined by the W3C XML Schema Part 2: Datatypes recommendation.

使用此XmlReader方法Use this XmlReader method 傳回這個 CLR 類型To return this CLR type
ReadContentAsBooleanReadElementContentAsBooleanReadContentAsBoolean and ReadElementContentAsBoolean Boolean
ReadContentAsDateTimeReadElementContentAsDateTimeReadContentAsDateTime and ReadElementContentAsDateTime DateTime
ReadContentAsDoubleReadElementContentAsDoubleReadContentAsDouble and ReadElementContentAsDouble Double
ReadContentAsLongReadElementContentAsLongReadContentAsLong and ReadElementContentAsLong Int64
ReadContentAsIntReadElementContentAsIntReadContentAsInt and ReadElementContentAsInt Int32
ReadContentAsStringReadElementContentAsStringReadContentAsString and ReadElementContentAsString String
ReadContentAsReadElementContentAsReadContentAs and ReadElementContentAs 您使用指定的型別returnType參數The type you specify with the returnType parameter
ReadContentAsObjectReadElementContentAsObjectReadContentAsObject and ReadElementContentAsObject 所指定最適當的類型XmlReader.ValueType屬性。The most appropriate type, as specified by the XmlReader.ValueType property. 請參閱System.Xml 類別中的型別支援對應資訊。See Type Support in the System.Xml Classes for mapping information.

如果項目輕鬆無法轉換為 CLR 型別中,但會因為其格式,您可以使用結構描述對應,以確保成功的轉換。If an element can't easily be converted to a CLR type because of its format, you can use a schema mapping to ensure a successful conversion. 下列範例會使用為.xsd 檔轉換hire-date項目xs:date類型,然後使用ReadElementContentAsDateTime方法,以傳回此元素作為DateTime物件。The following example uses an .xsd file to convert the hire-date element to the xs:date type, and then uses the ReadElementContentAsDateTime method to return the element as a DateTime object.

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

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

結構描述 (hireDate.xsd):Schema (hireDate.xsd):

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

程式碼:Code:

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

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

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

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

輸出:Output:

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

非同步程式設計Asynchronous programming

大部分的XmlReader方法有非同步對應項目具有"Async"結尾的方法名稱。Most of the XmlReader methods have asynchronous counterparts that have "Async" at the end of their method names. 例如,非同步的對等ReadContentAsObjectReadContentAsObjectAsyncFor example, the asynchronous equivalent of ReadContentAsObject is ReadContentAsObjectAsync.

下列方法可以搭配非同步方法呼叫:The following methods can be used with asynchronous method calls:

下列各節說明非同步方法,不需要非同步對應項目使用方式。The following sections describe asynchronous usage for methods that don't have asynchronous counterparts.

ReadStartElement 方法ReadStartElement method

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

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

ReadEndElement 方法ReadEndElement method

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

ReadToNextSibling 方法ReadToNextSibling method

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

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

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

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

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

    ' find the next sibling
    Dim nt As XmlNodeType
    Do

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

    Return False

End Function

ReadToFollowing 方法ReadToFollowing method

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

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

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

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

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

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

    Return False
End Function

ReadToDescendant 方法ReadToDescendant method

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

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

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

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

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

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

    Return False
End Function

安全性考量Security considerations

使用時,請考慮下列XmlReader類別:Consider the following when working with the XmlReader class:

  • 從擲回的例外狀況XmlReader可能會洩露到您的應用程式的路徑資訊,您可能不想反昇。Exceptions thrown from the XmlReader can disclose path information that you might not want bubbled up to your app. 您的應用程式必須攔截例外狀況,並適當地處理它們。Your app must catch exceptions and process them appropriately.

  • 請勿啟用 DTD 處理,如果您擔心阻絕服務問題,或如果您正在處理不受信任的來源。Do not enable DTD processing if you're concerned about denial of service issues or if you're dealing with untrusted sources. 預設為停用 DTD 處理XmlReader所建立的物件Create方法。DTD processing is disabled by default for XmlReader objects created by the Create method.

    如果已啟用 DTD 處理,則可使用 XmlSecureResolver 限制 XmlReader 可存取的資源。If you have DTD processing enabled, you can use the XmlSecureResolver to restrict the resources that the XmlReader can access. 您也可以設計您的應用程式,讓 XML 處理具有記憶體和時間限制。You can also design your app so that the XML processing is memory and time constrained. 比方說,您可以設定逾時限制在您的 ASP.NET 應用程式。For example, you can configure time-out limits in your ASP.NET app.

  • XML 資料可以包括外部資源的參考,如結構描述檔案。XML data can include references to external resources such as a schema file. 根據預設,使用解析外部資源XmlUrlResolver與不具使用者認證的物件。By default, external resources are resolved by using an XmlUrlResolver object with no user credentials. 您可以透過執行下列其中一項作業,進一步保護它:You can secure this further by doing one of the following:

  • ProcessInlineSchemaProcessSchemaLocation驗證旗標XmlReaderSettings物件不預設設定。The ProcessInlineSchema and ProcessSchemaLocation validation flags of an XmlReaderSettings object aren't set by default. 在處理來自不受信任來源的 XML 資料時,這有助於保護 XmlReader,防止其遭受以結構描述為基礎的攻擊。This helps to protect the XmlReader against schema-based attacks when it is processing XML data from an untrusted source. 當設定這些旗標時,XmlResolver 物件的 XmlReaderSettings 可用於解析在 XmlReader 的執行個體文件中發現的結構描述位置。When these flags are set, the XmlResolver of the XmlReaderSettings object is used to resolve schema locations encountered in the instance document in the XmlReader. 如果XmlResolver屬性設定為null,結構描述位置不是解析即使ProcessInlineSchemaProcessSchemaLocation設定驗證旗標。If the XmlResolver property is set to null, schema locations aren't resolved even if the ProcessInlineSchema and ProcessSchemaLocation validation flags are set.

    驗證期間加入的結構描述會加入新型別,並可變更要驗證之物件的驗證結果。Schemas added during validation add new types and can change the validation outcome of the document being validated. 因此,外部結構描述應僅從受信任的來源解析。As a result, external schemas should only be resolved from trusted sources.

    建議您停用ProcessIdentityConstraints驗證高可用性的情況下,針對文件的大部分具有識別條件約束的結構描述中的不受信任、 大型 XML 文件時的旗標。We recommend disabling the ProcessIdentityConstraints flag when validating untrusted, large XML documents in high availability scenarios against a schema that has identity constraints over a large part of the document. 預設會啟用此旗標。This flag is enabled by default.

  • XML 資料可以包含需要相當長時間來處理的大量屬性、命名空間宣告、巢狀項目等。XML data can contain a large number of attributes, namespace declarations, nested elements and so on that require a substantial amount of time to process. 若要傳送至輸入的大小限制XmlReader,您可以:To limit the size of the input that is sent to the XmlReader, you can:

  • ReadValueChunk方法可用來處理大型資料流的資料。The ReadValueChunk method can be used to handle large streams of data. 此方法每次會讀取較少數量的字元,而不是為整個值配置單一字串。This method reads a small number of characters at a time instead of allocating a single string for the whole value.

  • 讀取 XML 文件具有大量唯一本機名稱、 命名空間或前置詞時,會發生問題。When reading an XML document with a large number of unique local names, namespaces, or prefixes, a problem can occur. 如果您使用的類別,衍生自XmlReader,而且您呼叫LocalNamePrefix,或NamespaceURI每個項目的屬性,傳回的字串會新增至NameTableIf you are using a class that derives from XmlReader, and you call the LocalName, Prefix, or NamespaceURI property for each item, the returned string is added to a NameTable. 所持有的集合NameTable永遠不會減少的大小,建立字串控制代碼的虛擬記憶體流失。The collection held by the NameTable never decreases in size, creating a virtual memory leak of the string handles. 這一個緩和策略是衍生自NameTable類別並強制執行最大的大小配額。One mitigation for this is to derive from the NameTable class and enforce a maximum size quota. (沒有任何方法可防止使用NameTable,或切換NameTable配額已滿時)。(There is no way to prevent the use of a NameTable, or to switch the NameTable when it is full). 另一個的緩和措施是避免使用提到的屬性,改用MoveToAttribute方法IsStartElement方法這些方法可能; 不傳回字串,並因此避免量問題NameTable集合。Another mitigation is to avoid using the properties mentioned and instead use the MoveToAttribute method with the IsStartElement method where possible; those methods don't return strings and thus avoid the problem of overfilling the NameTable collection.

  • XmlReaderSettings 物件可以包含機密資訊 (如使用者認證)。XmlReaderSettings objects can contain sensitive information such as user credentials. 不受信任的元件可能會使用 XmlReaderSettings 物件及其使用者認證,建立 XmlReader 物件來讀取資料。An untrusted component could use the XmlReaderSettings object and its user credentials to create XmlReader objects to read data. 快取時請小心XmlReaderSettings物件,或傳遞時XmlReaderSettings元件之間的物件。Be careful when caching XmlReaderSettings objects, or when passing the XmlReaderSettings object from one component to another.

  • 請不要接受來自不受信任來源的支援元件,如 NameTableXmlNamespaceManagerXmlResolver 物件。Do not accept supporting components, such as NameTable, XmlNamespaceManager, and XmlResolver objects, from an untrusted source.

建構函式

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

初始化 XmlReader 類別的新執行個體。Initializes a new instance of the XmlReader class.

屬性

AttributeCount AttributeCount AttributeCount AttributeCount

在衍生類別中覆寫時,取得目前節點上的屬性數目。When overridden in a derived class, gets the number of attributes on the current node.

BaseURI BaseURI BaseURI BaseURI

在衍生類別中覆寫時,取得目前節點的基底 URI。When overridden in a derived class, gets the base URI of the current node.

CanReadBinaryContent CanReadBinaryContent CanReadBinaryContent CanReadBinaryContent

取得值,這個值表示 XmlReader 是否會實作二進位內容讀取方法。Gets a value indicating whether the XmlReader implements the binary content read methods.

CanReadValueChunk CanReadValueChunk CanReadValueChunk CanReadValueChunk

取得值,表示 XmlReader 是否會實作 ReadValueChunk(Char[], Int32, Int32) 方法。Gets a value indicating whether the XmlReader implements the ReadValueChunk(Char[], Int32, Int32) method.

CanResolveEntity CanResolveEntity CanResolveEntity CanResolveEntity

取得值,指出這個讀取器是否可以剖析和解析實體。Gets a value indicating whether this reader can parse and resolve entities.

Depth Depth Depth Depth

在衍生類別中覆寫時,取得 XML 文件中目前節點的深度。When overridden in a derived class, gets the depth of the current node in the XML document.

EOF EOF EOF EOF

在衍生類別中覆寫時,取得指出讀取器是否在資料流結尾的值。When overridden in a derived class, gets a value indicating whether the reader is positioned at the end of the stream.

HasAttributes HasAttributes HasAttributes HasAttributes

取得值,表示目前節點是否具有任何屬性。Gets a value indicating whether the current node has any attributes.

HasValue HasValue HasValue HasValue

在衍生類別中覆寫時,取得指出目前節點是否具有 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().

適用於

另請參閱