XElement NullReferenceException

I have the following code.

 XElement opCoOptOff = doc.Descendants(ns + "OpCoOptOff").FirstOrDefault();
 String opCo = opCoOptOff.Element(ns + "strOpCo").Value;

Now, if the element I'm returning is null, I get a NullReferenceException, because XElement is null. So I changed it to the following.

String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
 if(opCoOptOff != null)
        {
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;

I hope that there should be a more elegant way to do this, as this scenario arises often, and I would like to avoid this type of check every time there is a problem. Any help would be greatly appreciated.

+3
source share
2 answers

You can write extension methodand use it anywhere:

public static class XDocumentExtension
{
   public static string GetSubElementValue(this XElement element, string item)
   {
        if(element != null && element.Value != null)
        {
           if (element.Element(item) != null)
           {
              return element.Element(item).Value;
           }
        }
        return null;
   }

   public static XElement GetElement(this XElement element, string item)
   {
        if (element != null)
            return element.Element(item);

        return null;
   }

   public static XElement GetElement(this XDocument document, string item)
   {
        if (document != null)
           return document.Descendants("item").FirstOrDefault();
        return null;
   }
}

Use it as:

String opCo = opCoOptOff.Element(ns + "strOpCo").GetSubElementValue(ns + "strOpCo");

You can also add other extensions for your purpose.

: , , , add other extensions for your purpose. , , Element, , , , , XDocumentExtension, .

+2

XElement : http://msdn.microsoft.com/en-us/library/bb155263.aspx

String opCo = opCoOptOff.Element(ns + "strOpCo").Value;

string opCo = (string) opCoOptOff.Element(ns + "strOpCo");
+1

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


All Articles