Retrieves the value of a integer 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 integer 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;//  w ww.j  av a 2  s.  c o  m

public class Main{
        /// <summary>
      /// Retrieves the value of a integer attribute on an XML element, returning a default value if it is not found.
      /// The attribute's value may be represented in either decimal or hexadecimal.
      /// </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 value, or the default value if the attribute was not found.</returns>
      /// <exception cref="FormatException">Thrown if the attribute does not represent an integer.</exception>
      /// <seealso cref="ParseNumber"/>
      public static int GetNumericAttribute (XElement element, string name, int defaultValue)
      {
         XAttribute attribute = element.Attribute(name);
         if ( attribute == null )
            return defaultValue;

         int result;
         if ( ParseNumber(attribute.Value, out result) )
            return result;

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

Related Tutorials