The following extension method returns 0 if the element is missing, the element is empty or contains a string that cannot be parsed for an integer:
public static int ToInt(this XElement x, string name) { int value; XElement e = x.Element(name); if (e == null) return 0; else if (int.TryParse(e.Value, out value)) return value; else return 0; }
You can use it as follows:
... Year = g.ToInt("r3dim_value"), ...
Or, if you are willing to consider the cost of reflection and accept the default value of any type of value, you can use this extension method:
public static T Cast<T>(this XElement x, string name) where T : struct { XElement e = x.Element(name); if (e == null) return default(T); else { Type t = typeof(T); MethodInfo mi = t.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder, new Type[] { typeof(string), t.MakeByRefType() }, null); var paramList = new object[] { e.Value, null }; mi.Invoke(null, paramList); return (T)paramList[1];
and use it:
... Year = g.Cast<int>("r3dim_value"), ...
horgh
source share