view Xml/XmlTools.cs @ 26:14f3daf48ba5

Re #18 - Migrate XML handling methods to core utils * Make double parsing method public
author IBBoard <dev@ibboard.co.uk>
date Sat, 28 Mar 2009 20:37:40 +0000
parents 148edabc9c73
children 4ea1fc351533
line wrap: on
line source

//  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;
using System.Xml;

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>
		public static 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;
		}
	}
}