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

发布于 2024-07-09 03:19:59 字数 235 浏览 9 评论 0原文

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

那么,考虑到这一点,将这样的值解析为布尔值的最佳方法是什么?

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

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.

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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

韵柒 2024-07-16 03:19:59

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

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

爱你不解释 2024-07-16 03:19:59

使用 CBool​​ 代替 Boolean.Parse 应该可以解决问题:尽管您必须将其嵌入到 try/catch 块中(这不会使用 Boolean.TryParse 时不需要),它将成功转换大多数“合理”布尔值,包括 true/false 和 0/1。

编辑:正如评论中指出的,这个答案对于 C# 程序员来说有点无用,因为 CBool​​ 是 VB 主义。 它映射到 Microsoft.VisualBasic.CompilerServices.Conversions::ToBoolean,不适合一般使用。 这使得在接受的答案中指出的 XMLConvert 类成为更好的选择。

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

Edit: as pointed out in a comment, this answer is kinda useless for C# programmers, as CBool is 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.

北方的韩爷 2024-07-16 03:19:59

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

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

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

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, 0 or 1 will still throw a "Bad Format" exception (as it should be).

记忆里有你的影子 2024-07-16 03:19:59
return value === 'true' || Number(value)
return value === 'true' || Number(value)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文