Retrieves the value of an 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 an 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 w w  w.ja  v  a2  s.c  om

public class Main{
        /// <summary>
      /// Retrieves the value of an 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 value, or the default value if the attribute was not found.</returns>
      public static string GetStringAttribute (XElement element, string name, string defaultValue)
      {
         XAttribute attribute = element.Attribute(name);
         if ( attribute != null )
            return attribute.Value;
         return defaultValue;
      }
        /// <summary>
      /// Retrieves the value of an attribute on an XML element.
      /// An exception will be thrown if the attribute doesn't exist.
      /// </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 value.</returns>
      /// <exception cref="ArgumentException">Thrown if the attribute is missing.</exception>
      public static string GetStringAttribute (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.");
         return attribute.Value;
      }
}

Related Tutorials