changeset 24:5cbf8bbf9b05

Re #18 - Migrate XML handling methods to core utils * Add methods to get an attribute value as an integer or double to core
author IBBoard <dev@ibboard.co.uk>
date Sat, 28 Mar 2009 20:35:43 +0000
parents fb4fdab841db
children 148edabc9c73
files Xml/XmlTools.cs
diffstat 1 files changed, 75 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /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
+{
+	/// <summary>
+	/// Some basic tools for handling XML files and retrieving their values
+	/// </summary>
+	public class XmlTools
+	{			
+		/// <summary>
+		/// Gets the value of an attribute of an element as an integer. Throws a FormatException if the attribute is not an integer.
+		/// </summary>
+		/// <param name="elem">
+		/// The <see cref="XmlElement"/> to get the attribute value of
+		/// </param>
+		/// <param name="attributeName">
+		/// The name of the attribute to get as an integer
+		/// </param>
+		/// <returns>
+		/// The value of the attribute as an integer
+		/// </returns>
+		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")));
+			}
+		}
+							
+		/// <summary>
+		/// Gets the value of an attribute of an element as a double. Throws a FormatException if the attribute is not a double.
+		/// </summary>
+		/// <param name="elem">
+		/// The <see cref="XmlElement"/> to get the attribute value of
+		/// </param>
+		/// <param name="attributeName">
+		/// The name of the attribute to get as a double
+		/// </param>
+		/// <returns>
+		/// The value of the attribute as an double
+		/// </returns>
+		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;
+		}
+	}
+}