Retrieves the value of a boolean ("true" or "false") attribute on an XML element, returning a default value if it is not found. - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Retrieves the value of a boolean ("true" or "false") attribute on an XML element, returning a default value if it is not found.

Demo Code


using System.Xml.Linq;
using System.Globalization;
using System;//from ww  w.  j  ava2 s  . c  o m

public class Main{
        /// <summary>
      /// Retrieves the value of a boolean ("true" or "false") attribute on an XML element, returning a default value if it is not found.
      /// </summary>
      /// <param name="element">The XML element that holds the attribute.</param>
      /// <param name="name">The name of the attribute to get the value of.</param>
      /// <param name="defaultValue">The value to return if the attribute is not found.</param>
      /// <returns>The attribute's corresponding bool value, or the default value if the attribute was not found.</returns>
      /// <exception cref="FormatException">Thrown if the attribute does not represent a boolean.</exception>
      public static bool GetBoolAttribute (XElement element, string name, bool defaultValue)
      {
         XAttribute attribute = element.Attribute(name);
         if ( attribute == null )
            return defaultValue;

         if ( attribute.Value.ToLower() == "true" )
            return true;
         if ( attribute.Value.ToLower() == "false" )
            return false;

         throw new FormatException("A(n) \"" + element.Name + "\" element has an invalid \"" + name + "\" attribute: " + attribute.Value);
      }
        /// <summary>
      /// Retrieves the value of a boolean ("true" or "false") attribute on an XML element.
      /// An exception will be thrown if the attribute doesn't exist or is invalid.
      /// </summary>
      /// <param name="element">The XML element that holds the attribute.</param>
      /// <param name="name">The name of the attribute to get the value of.</param>
      /// <returns>The attribute's corresponding bool value.</returns>
      /// <exception cref="FormatException">Thrown if the attribute does not represent a boolean.</exception>
      public static bool GetBoolAttribute (XElement element, string name)
      {
         XAttribute attribute = element.Attribute(name);
         if ( attribute == null )
            throw new ArgumentException("A(n) \"" + element.Name + "\" element is missing the required \"" + name + "\" attribute.");

         if ( attribute.Value.ToLower() == "true" )
            return true;
         if ( attribute.Value.ToLower() == "false" )
            return false;

         throw new FormatException("A(n) \"" + element.Name + "\" element has an invalid \"" + name + "\" attribute: " + attribute.Value);
      }
}

Related Tutorials