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.

1public static T GetElementValue<T>(XElement parent, string elementId, T defaultValue) where T : IConvertible
2{
3 XElement element = parent.Element(elementId);
4 if (element != null)
5 return (T)Convert.ChangeType(element.Value, typeof(T), CultureInfo.InvariantCulture);
6 else
7 return defaultValue;
8}

I’ve been using this combined with .Net 3.0 object initializers to re-hydrate objects from Xml with safe values, like…

1var myClass = new MyClass()
2{
3 Name = GetElementValue(parent, "Name", String.Empty),
4 IsDefault = GetElementValue(parent, "IsDefault ", true),
5 YearsLeft = GetElementValue(parent, "Yearsleft", 100)
6}