C# How to convert XML to Boolean

If you program using C# and store your data in an XML file, then it also happens very often that you have to store values of the Boolean/Bool type in the XML file. These can be, for example, the states of any checkboxes that the user has clicked in the program or a UserControl.

Assign XML string to Boolean

If you now load such an XML file and want to read the data back into your program, you first get only a string variable, which you have to convert to Boolean.

Fortunately, the System.XML namespace provides a suitable method here, so that you do not have to program the type conversion yourself. For this and other type conversions there is the class XmlConvert, which provides a set of static methods to convert XML strings back to the correct string.

A Boolean value is stored in the XML file as a string of the form TRUE/FALSE, True/False or true/false. The code for converting can then look like this:

XmlNode? xmlMyBool = nd.SelectSingleNode("MyBoolValue");
if (xmlEditable != null)
   bool myBoolean = XmlConvert.ToBoolean(xmlMyBool.InnerText.ToLower());

The XMLConvert.ToBoolean function understands only lowercase values. However, it may happen that it is capitalized in the XML file. Then the method throws an exception. For this reason you should normalize the passed string to lower case with the method .toLower().

Leave a Reply

Your email address will not be published. Required fields are marked *