解析 XML 布尔属性(在 .NET 中)的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/265425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:30:54  来源:igfitidea点击:

What is the best way to parse an XML boolean attribute (in .NET)?

.netxml.net-2.0booleanxml-attribute

提问by James Curran

An XML attribute declared as xs:boolean can acceptable be "true", "false", "0" or "1". However, in .NET, Boolean.Parse() will only accept "true" or "false". If it sees a "0" or "1", it throws a "Bad Format" exception.

声明为 xs:boolean 的 XML 属性可以是“true”、“false”、“0”或“1”。但是,在 .NET 中,Boolean.Parse() 将只接受“true”或“false”。如果它看到“0”或“1”,则会引发“格式错误”异常。

So, given that, what's the best way to parse such a value into a Boolean?

那么,鉴于此,将此类值解析为布尔值的最佳方法是什么?

(Unfortunately, I'm limited to .NET 2.0 solutions, but if v3.5 offers something, I'd love to hear about it.)

(不幸的是,我仅限于 .NET 2.0 解决方案,但如果 v3.5 提供了一些东西,我很想听听。)

回答by Panos

I think that XmlConverthas all the methods for converting between common language runtime types and XML types. Especially XmlConvert.ToBooleanhandles exactly the boolean values (valid strings are "1" or "true" for true and "0" or "false" for false).

我认为XmlConvert具有在公共语言运行时类型和 XML 类型之间转换的所有方法。特别是XmlConvert.ToBoolean精确处理布尔值(有效字符串为“1”或“true”表示真,“0”或“false”表示假)。

回答by mdb

Using CBoolinstead of Boolean.Parseshould do the trick: although you'll have to embed it in a try/catchblock (which wouldn't be required when using Boolean.TryParse), it will successfully convert most 'sensible' boolean values, including true/false and 0/1.

使用CBool而不是Boolean.Parse应该可以解决问题:尽管您必须将它嵌入到一个try/catch块中(使用时不需要Boolean.TryParse),但它会成功转换大多数“合理”的布尔值,包括真/假和 0/1。

Edit: as pointed out in a comment, this answer is kinda useless for C# programmers, as CBoolis a VB-ism. It maps to Microsoft.VisualBasic.CompilerServices.Conversions::ToBoolean, which is not suitable for general consumption. Which makes the XMLConvert class pointed out in the accepted answer an even better alternative.

编辑:正如评论中指出的那样,这个答案对 C# 程序员来说有点没用,就像CBoolVB 主义一样。它映射到Microsoft.VisualBasic.CompilerServices.Conversions::ToBoolean,不适合一般消费。这使得 XMLConvert 类在接受的答案中指出一个更好的选择。

回答by Treb

Sanitise the data before attempting to parse it:

在尝试解析数据之前清理数据:

 string InnerText = yourXmlNode.InnerText;    
if (InnerText.Equals("0"))
    InnerText = "false";
else if (InnerText.Equals("1"))
    InnerText = "true";

Any other entry than true, false, 0or 1will still throw a "Bad Format" exception (as it should be).

truefalse01之外的任何其他条目仍将引发“格式错误”异常(应该如此)。

回答by Bananas

return value === 'true' || Number(value)