internal static T ExtractAttribute<T>( this XElement element, string attributeName, bool throwIfAttributeNotFound = false )
{
XAttribute attribute = element.Attribute( attributeName );
if ( attribute == null )
{
if ( throwIfAttributeNotFound )
throw new ApplicationException( string.Format( "Attribute {0} could not be found in element {1}", attributeName, element ) );
return default( T );
}
try
{
Type type = typeof( T );
Type nullableType = Nullable.GetUnderlyingType( type );
if ( nullableType != null )
{
return ( T )Convert.ChangeType( attribute.Value, nullableType );
}
return ( T )Convert.ChangeType( attribute.Value, type );
}
catch ( Exception )
{
throw new ApplicationException( string.Format( "Could not convert value {0} to type {1} for attribute {2} in element {3}",
attribute.Value, typeof( T ), attributeName, element ) );
}
}