Sunday, August 02, 2009
Sunday, August 02, 2009 2:24:20 AM (GMT Daylight Time, UTC+01:00) (C# | Utilities)

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)
}
OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, em, i, strike, strong, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Live Comment Preview

search

categories

on this page

ads

archive

Total Posts: 97
This Year: 3
This Month: 0
This Week: 0
Comments: 92