document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. internal static T ExtractAttribute<T>( this XElement element, string attributeName, bool throwIfAttributeNotFound = false )
  2. {
  3.     XAttribute attribute = element.Attribute( attributeName );
  4.     if ( attribute == null )
  5.     {
  6.         if ( throwIfAttributeNotFound )
  7.             throw new ApplicationException( string.Format( "Attribute {0} could not be found in element {1}", attributeName, element ) );
  8.  
  9.         return default( T );
  10.     }
  11.  
  12.     try
  13.     {
  14.         Type type = typeof( T );
  15.         Type nullableType = Nullable.GetUnderlyingType( type );
  16.         if ( nullableType != null )
  17.         {
  18.             return ( T )Convert.ChangeType( attribute.Value, nullableType );
  19.         }
  20.  
  21.         return ( T )Convert.ChangeType( attribute.Value, type );
  22.     }
  23.     catch ( Exception )
  24.     {
  25.         throw new ApplicationException( string.Format( "Could not convert value {0} to type {1} for attribute {2} in element {3}",
  26.             attribute.Value, typeof( T ), attributeName, element ) );
  27.     }
  28. }
');