CSharp examples for System.Xml:XML Element
Retrieves the value of a floating-point attribute on an XML element, returning a default value if it is not found.
using System.Xml.Linq; using System.Globalization; using System;/* w w w . j a v a2s . co m*/ public class Main{ /// <summary> /// Retrieves the value of a floating-point 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> /// <exception cref="FormatException">Thrown if the attribute does not represent a floating-point value.</exception> public static float GetFloatAttribute (XElement element, string name, float defaultValue) { XAttribute attribute = element.Attribute(name); if ( attribute == null ) return defaultValue; float result; if ( float.TryParse(attribute.Value, out result) ) return result; throw new FormatException("A(n) \"" + element.Name + "\" element has an invalid \"" + name + "\" attribute: " + attribute.Value); } /// <summary> /// Retrieves the value of a floating-point attribute on an XML element. /// </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, or the default value if the attribute was not found.</returns> /// <exception cref="ArgumentException">Thrown if the attribute is missing.</exception> /// <exception cref="FormatException">Thrown if the attribute does not represent a floating-point value.</exception> public static float GetFloatAttribute (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."); float result; if ( float.TryParse(attribute.Value, out result) ) return result; throw new FormatException("A(n) \"" + element.Name + "\" element has an invalid \"" + name + "\" attribute: " + attribute.Value); } }