C# LINQ到XML错误:对象引用未设置为对象的实例

C# LINQ到XML错误:对象引用未设置为对象的实例,c#,xml,linq,C#,Xml,Linq,我试图获取一些角色信息,但是第一个节点没有元素“projectRoleType”,我想跳过该节点,只获取具有“projectRoleType”和“categoryId”的节点。每次我尝试检查时都会出现错误:对象引用未设置为对象的实例。我没在做什么 var _role = from r1 in loaded.Descendants("result") let catid = (string)r1.Element("projectRoles").Ele

我试图获取一些角色信息,但是第一个节点没有元素“projectRoleType”,我想跳过该节点,只获取具有“projectRoleType”和“categoryId”的节点。每次我尝试检查时都会出现错误:对象引用未设置为对象的实例。我没在做什么

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));
            }

如果尝试访问成员或调用
null
方法,则会出现NullReferenceException。例如,
r1.Element(“projectRoles”).Element(“projectRoleType”)
如果projectRoles中没有projectRoleType元素,则返回
null
,因此从
null
获取categoryId子级会引发异常

添加空检查:

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 ...