# HG changeset patch # User IBBoard # Date 1238272543 0 # Node ID 5cbf8bbf9b05f866abb1ea557a4bfbaafc68fb88 # Parent fb4fdab841db5f82a4450adbf32af60b6d7236c7 Re #18 - Migrate XML handling methods to core utils * Add methods to get an attribute value as an integer or double to core diff -r fb4fdab841db -r 5cbf8bbf9b05 Xml/XmlTools.cs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Xml/XmlTools.cs Sat Mar 28 20:35:43 2009 +0000 @@ -0,0 +1,75 @@ +// This file (XmlTools.cs) is a part of the IBBoard library and is copyright 2009 IBBoard +// +// The file and the library/program it is in are licensed under the GNU LGPL license, either version 3 of the License or (at your option) any later version. Please see COPYING.LGPL for more information and the full license. +// + +using System; + +namespace IBBoard.Xml +{ + /// + /// Some basic tools for handling XML files and retrieving their values + /// + public class XmlTools + { + /// + /// Gets the value of an attribute of an element as an integer. Throws a FormatException if the attribute is not an integer. + /// + /// + /// The to get the attribute value of + /// + /// + /// The name of the attribute to get as an integer + /// + /// + /// The value of the attribute as an integer + /// + public static int GetIntValueFromAttribute(XmlElement elem, string attributeName) + { + try + { + return int.Parse(elem.GetAttribute(attributeName)); + } + catch(FormatException) + { + throw new FormatException(String.Format("Attribute '{0}' of {1} with ID {2} was not a valid number", attributeName, elem.Name, elem.GetAttribute("id"))); + } + } + + /// + /// Gets the value of an attribute of an element as a double. Throws a FormatException if the attribute is not a double. + /// + /// + /// The to get the attribute value of + /// + /// + /// The name of the attribute to get as a double + /// + /// + /// The value of the attribute as an double + /// + private double GetDoubleValueFromAttribute(XmlElement elem, string attributeName) + { + double doubleVal = double.NaN; + string attribValue = elem.GetAttribute(attributeName); + + if (attribValue == "INF") + { + doubleVal = double.PositiveInfinity; + } + else + { + try + { + return int.Parse(attribValue); + } + catch(FormatException) + { + throw new FormatException(String.Format("Attribute '{0}' of {1} with ID {2} was not a valid number", attributeName, elem.Name, elem.GetAttribute("id"))); + } + } + + return doubleVal; + } + } +}