Tuesday, 7 February 2012

LINQ to XML Enum Extension Method Converter

Below are easy to use extension methods to extract a generic enum from an XML attribute using LINQ to XML:


    
public static class ExtensionMethods
    {
        public static string SafeAttribute(this XElement element, string key)
        {
            var attribute = element.Attribute(key);
            return attribute != null ? element.Attribute(key).Value : "";
        }

        public static T SafeAttribute<T>(this XElement element, string key)
        {
            var attribute = SafeAttribute(element, key);
            return !string.IsNullOrEmpty(attribute) ? (T)Enum.Parse(typeof(T), attribute) : default(T);
        }
    }

Any this is how you would call it:

var xml = XDocument.Load(filePath);
var e = xml.Element("Item").SafeAttribute<MyEnum>("myKey");

No comments: