[ACCEPTED]-What is the best way to parse an XML boolean attribute (in .NET)?-xml-attribute
I think that XmlConvert has all the methods for converting 5 between common language runtime types and 4 XML types. Especially
XmlConvert.ToBoolean handles exactly the 3 boolean values (valid strings are "1" or 2 "true" for true and "0" or 1 "false" for false).
CBool instead of
Boolean.Parse should do the trick: although 10 you'll have to embed it in a
try/catch block (which 9 wouldn't be required when using
Boolean.TryParse), it will 8 successfully convert most 'sensible' boolean 7 values, including true/false and 0/1.
Edit: as 6 pointed out in a comment, this answer is 5 kinda useless for C# programmers, as
CBool is 4 a VB-ism. It maps to
Microsoft.VisualBasic.CompilerServices.Conversions::ToBoolean, which is not suitable 3 for general consumption. Which makes the 2 XMLConvert class pointed out in the accepted 1 answer an even better alternative.
Sanitise the data before attempting to parse 3 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 2 throw a "Bad Format" exception (as it should 1 be).
return value === 'true' || Number(value)
More Related questions