Get XElement Value with Default
Submitted on Aug 01, 2009, 6:24 p.m.
Thanks to this post at .Net Dojo , here’s a utility method for getting a safe value from an XElement, returning a default value if the element was not found.
public static T GetElementValue<T>(XElement parent, string elementId, T defaultValue) where T : IConvertible{ XElement element = parent.Element(elementId); if (element != null) return (T)Convert.ChangeType(element.Value, typeof(T), CultureInfo.InvariantCulture); else return defaultValue; }
I’ve been using this combined with .Net 3.0 object initializers to re-hydrate objects from Xml with safe values, like…
var myClass = new MyClass() { Name = GetElementValue(parent, "Name", String.Empty), IsDefault = GetElementValue(parent, "IsDefault ", true), YearsLeft = GetElementValue(parent, "Yearsleft", 100)}