Ken
Ken

Reputation: 171

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 return is null, I am getting a NullReferenceException since the 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 am hoping there has to be a more elegant way to do this since this scenario comes up often and I would like to avoid doing this type of check every time there is an issue. Any assistance would be greatly appreciated

Upvotes: 3

Views: 1353

Answers (2)

mark w
mark w

Reputation: 81

You can actually cast the XElement directly to a string: http://msdn.microsoft.com/en-us/library/bb155263.aspx

so

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

could be

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

Upvotes: 1

Saeed Amiri
Saeed Amiri

Reputation: 22555

You can write an extension method and 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");

Also you can add other extensions for your purpose.

Edit: I'd updated answer but if you read it carefully before I wrote you can add other extensions for your purpose. I wrote this because I guess you may be want to call on null objects Element, I don't know what's exact situation of yours but I add some code for more clarification, depend on your situation complete the XDocumentExtension class, and one note extension methods can work on null objects.

Upvotes: 2

Related Questions