XmlReader.ReadContentAsBoolean 方法

定義

Boolean 的形式,讀取目前位置的文字內容。

public:
 virtual bool ReadContentAsBoolean();
public virtual bool ReadContentAsBoolean ();
abstract member ReadContentAsBoolean : unit -> bool
override this.ReadContentAsBoolean : unit -> bool
Public Overridable Function ReadContentAsBoolean () As Boolean

傳回

Boolean 物件形式的文字內容。

例外狀況

嘗試的轉換無效。

字串格式無效。

在先前的非同步作業完成前呼叫了 XmlReader 方法。 在此情況下,會擲回 InvalidOperationException 與「非同步作業已經在進行中」的訊息。

範例

下列範例會 ReadContentAsBoolean 使用 方法來讀取 屬性做為 Boolean 值。

using (XmlReader reader = XmlReader.Create("dataFile_2.xml")) {
      reader.ReadToDescendant("item");
      do {
          reader.MoveToAttribute("sale-item");
          Boolean onSale = reader.ReadContentAsBoolean();
          if (onSale) {
             Console.WriteLine(reader["productID"]);
          }
      } while (reader.ReadToNextSibling("item"));	
}
Using reader As XmlReader = XmlReader.Create("dataFile_2.xml")
              
  reader.ReadToDescendant("item")
              
  Do
    reader.MoveToAttribute("sale-item")
    Dim onSale As [Boolean] = reader.ReadContentAsBoolean()
    If onSale Then
      Console.WriteLine(reader("productID"))
    End If
  Loop While reader.ReadToNextSibling("item")
          
End Using

該範例使用 dataFile_2.xml 檔案做為輸入。

<root>
  <item sale-item='true' productID='123456' colors='blue green black'>
    <price>9.95</price>
  </item>
  <item sale-item='false' productID='124390'>
    <price>5.95</price>
  </item>
  <item sale-item='true' productID='53298'>
    <price>12.95</price>
  </item>
</root>

備註

此方法會串連文字、空白字元、重大空白字元和 CDATA 區段,並略過任何批註或處理指示。 實體參考會自動解析。

如果內容類型為 xsd:boolean ,讀取器會傳回未收件匣 Boolean 的物件。 如果未輸入 xsd:boolean 內容,讀取器會根據W3C XML 架構第 2 部分:資料類型建議所定義的規則,嘗試將它 Boolean 轉換成 物件。

下表描述此方法如何處理每個節點類型。

XmlNodeType 傳回值 讀取器行為
Text

CDATA

Whitespace

SignificantWhitespace

EntityReference

EndEntity
文字、CDATA、泛空白字元及顯著泛空白字元節點的串連內容會轉換為要求的型別。 移至下一個開始項目或結尾項目標記。 實體參考會自動展開。
Attribute 與在屬性值上呼叫 XmlConvert.ToXxx 相同。 讀取器會保持在目前位置。
Comment

ProcessingInstruction
忽略處理指示 (PI) 或註解,並讀取 PI 或註解後面的串連文字內容。 移至下一個開始項目或結尾項目標記。 實體參考會自動展開。
EndElement 空字串。 讀取器會保持在目前位置。
Element

XmlDeclaration

None

Document

DocumentType

Notation

Entity

DocumentFragment
擲回 InvalidOperationException 未定義 (但讀取器通常會保持在目前位置)。

如需詳細資訊,請參閱 XmlReader 參考頁面和 W3C XML 架構第 2 部分:資料類型 建議。

適用於