Avoiding the Impact of a NullReferenceException When Using LINQ to XML

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 ?

+3
2

- Elements() Element() -, , . Extensions, - . :

var firstName = 
  root
    .Elements(ns + "Employee")
    .Elements(ns + "Identity")
    .Elements(ns + "Name")
    .Attributes(ns + "FirstName")
    .FirstOrDefault();

, - , () Name Identity Employee. .

( , ? , . , .)

+7

, . - , :

public static class XmlExtender
{
   public static XAttribute AttributeOrDefault(this XElement el, XName name, string defValue)
   {
      var v = el.Attribute(name);
      return v == null ? new XAttribute(name, defValue) : v;
   }

   public static string AttributeValue(this XElement el, XName name, string defValue)
   {
      var v = el.Attribute(name);
      return v == null ? defValue : v.Value;
   }
}

:

var firstName = root.ELement("elname")
                    .AttributeOrDefault("attrName", "N/A").Value;

:

var firstName = root.Element("elname")
                    .AttributeValue("attrName", "N/A");
+1

Source: https://habr.com/ru/post/1777268/


All Articles