XmlReader.ReadContentAsBoolean 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将当前位置的文本内容读作一个 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 | 返回值 | 读取者行为 |
|---|---|---|
TextCDATAWhitespaceSignificantWhitespaceEntityReferenceEndEntity |
文本、CDATA、空格和重要空白节点的串联内容转换为请求的类型。 | 移动到下一个起始元素或结束元素标记。 会自动扩展实体引用。 |
Attribute |
与调用 XmlConvert.ToXxx 属性值相同。 |
读取器将保留在当前位置。 |
CommentProcessingInstruction |
忽略处理指令(PI)或注释,并读取 PI 或注释后面的串联文本内容。 | 移动到下一个起始元素或结束元素标记。 会自动扩展实体引用。 |
EndElement |
空字符串。 | 读取器将保留在当前位置。 |
ElementXmlDeclarationNoneDocumentDocumentTypeNotationEntityDocumentFragment |
将引发 An InvalidOperationException 。 | 未定义,尽管读取器通常保留在当前位置。 |
有关详细信息,请参阅 XmlReader 参考页和 W3C XML 架构第 2 部分:数据类型 建议。