c# - Handling null XElements whilst parsing an XDocument -
is there better way of doing this:
private xelement getsafeelem(xelement elem, string key) { xelement safeelem = elem.element(key); return safeelem ?? new xelement(key); } private string getattributevalue(xattribute attrib) { return attrib == null ? "n/a" : attrib.value; } var elem = getsafeelem(elem, "hdhdhddh"); string foo = getattributevalue(e.attribute("fkfkf")); //attribute has fallback value
when parsing elements/attribute values xml document? in cases element may not found when doing like:
string foo (string)elem.element("fooelement").attribute("fooattribute").value
so object reference error occur (assuming element/attribute aren't found). same when trying access element value
not sure better approach, saw in codeproject post , thought might useful approach here.
its monadic solution using "with" extension method:
public static tresult with<tinput, tresult>(this tinput o, func<tinput, tresult> evaluator) tresult : class tinput : class { if (o == null) return null; return evaluator(o); }
and return extension method:
public static tresult return<tinput,tresult>(this tinput o, func<tinput, tresult> evaluator, tresult failurevalue) tinput: class { if (o == null) return failurevalue; return evaluator(o); }
and combining them both query this:
var myelement = element.with(x => x.element("fooelement")).return(x => x.attribute("fooattribute").value, "mydefaultvalue")
not sure prettier using simple extension methods guys suggested in previous posts, bit more generic , nice approach imo
Comments
Post a Comment