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

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


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


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.


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