I use a chain of method calls XElement.Element()to expand an XML document and pull out the attribute value:
XElement root = ...;
XNamespace ns = "...";
var firstName =
root
.Element(ns + "Employee")
.Element(ns + "Identity")
.Element(ns + "Name")
.Attribute(ns + "FirstName");
However, since the incoming document was not checked by the schema, it is possible that the incorrect document will cause NullReferenceExceptionif any of the expected intermediate elements do not exist.
Is there a way to avoid this risk while maintaining a concise code?
I can wrap the code above in the handler for NullReferenceException, however this seems to be wrong, and will also not specifically indicate where the failure occurred. Building an error information message will be manual, tedious, error prone, and a maintenance hazard.
XPath, , , , , XPath ?