Get Attribute With Conversion

image_pdfimage_print
   
 
//http://validationframework.codeplex.com/
//License:  Microsoft Permissive License (Ms-PL) v1.1  
using System;
using System.Xml;

namespace ValidationFramework.Extensions
{
    public static class XmlElementExtensions
    {
        /// <summary>
        /// weakly typed
        /// </summary>
        /// <param name="element"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        internal static object GetAttributeWithConversion(this XmlElement element, Type typeToConvertTo, string key)
        {
            if (!element.HasAttribute(key))
                throw new ArgumentOutOfRangeException(string.Format("The key &#039;{0}&#039; cannot be found in xml element.", key));

            var stringValue = element.GetAttribute(key);

            var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeToConvertTo);

            return converter.ConvertFromString(stringValue);
        }
   }
}

   
     


This entry was posted in XML-RPC. Bookmark the permalink.