How about using an extension method to encapsulate the missing attribute cases:
public static class XmlExtensions
{
public static T AttributeValueOrDefault(this XElement element, string attributeName, T defaultValue)
{
var attribute = element.Attribute(attributeName);
if (attribute != null && attribute.Value != null)
{
return (T)Convert.ChangeType(attribute.Value, typeof(T));
}
return defaultValue;
}
}
Note that this will only work if T
is a type to which string knows to convert via IConvertible. If you wanted to support more general conversion cases, you may need to look for a TypeConverter, as well. This will throw an exception if the type fails to convert. If you want those cases to return the default as well, you'll need to perform additional error handling.