Dan
Dan

Reputation: 23

LINQ to XML error: Object reference not set to an instance of an object

I am trying to grab some role information, the first node however does not have an element "projectRoleType" I want to skip over that one and only grab the ones that have a "projectRoleType" and "categoryId". Every way I try to check I always get the error: Object reference not set to an instance of an object. What am I not doing?

var _role = from r1 in loaded.Descendants("result")
                        let catid = (string)r1.Element("projectRoles").Element("projectRoleType").Element("categoryId")
                        where catid != null && catid == categoryId
                        select new
                        {
                            id = (string)r1.Element("projectRoles").Element("projectRoleType").Element("id"),
                            name = (string)r1.Element("fullName"),
                            contactId = (string)r1.Element("contactId"),
                            role_nm = (string)r1.Element("projectRoles").Element("projectRoleType").Element("name")
                        };
            foreach (var r in _role)
            {
                fields.Add(new IAProjectField(r.id, r.role_nm, r.name, r.contactId));
            }

Upvotes: 2

Views: 4204

Answers (1)

dtb
dtb

Reputation: 217243

You get a NullReferenceException if you try to access the member or invoke a method of null. For example, r1.Element("projectRoles").Element("projectRoleType") returns null if there is no projectRoleType element in projectRoles, so getting the categoryId child from null throws an exception.

Add a null check:

from r1 in loaded.Descendants("result")

let projectRoleType = r1.Element("projectRoles").Element("projectRoleType")
where projectRoleType != null

let catid = (string)projectRoleType.Element("categoryId")
where catid == categoryId

select ...

Upvotes: 4

Related Questions