view Xml/XmlTools.cs @ 25:148edabc9c73

Re #18 - Migrate XML methods to core utils * Add required "using"
author IBBoard <dev@ibboard.co.uk>
date Sat, 28 Mar 2009 20:36:20 +0000
parents 5cbf8bbf9b05
children 14f3daf48ba5
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>
		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;
		}
	}
}