Handling null XElements whilst parsing an XDocument <p>Is there a better way of doing something like this:</p> <pre><code>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 now has a fallback value </code></pre> <p>When parsing elements/attribute values from an XML document? In some cases the element may not be found when doing something like:</p> <pre><code>string foo (string)elem.Element("fooelement").Attribute("fooattribute").Value </code></pre> <p>So an object reference error would occur (assuming the element/attribute aren't found). Same when trying to access the element value</p>