LINQ to XML - 检查null?

aus*_*rge 1 c# xml linq linq-to-xml

我一直在使用LINQ大约2天,所以请耐心等待.

这是我目前的代码;

_resultList = (
from
    item in _documentRoot.Descendants("MyItems")
select
    new MyClass
    {
        XMLID = item.Attribute("id").Value
    }).ToList<MyClass>();
Run Code Online (Sandbox Code Playgroud)

大多数元素都有'id'属性,并且它们会成功添加到列表中.但是,有些人没有'id'.对于这些,我希望'id'只是一个空字符串.

在尝试访问该属性之前,如何检查该属性是否存在?谢谢

Ser*_*kiy 8

您不需要将属性存储在其他变量中.如果属性不存在,则铸造属性字符串返回null.使用null-coalescing运算符的功能,您可以提供默认值 - 空字符串:

from item in _documentRoot.Descendants("MyItems")
select new MyClass {
        XMLID = (string)item.Attribute("id") ?? ""
    }
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 5

您可以将其存储在变量中,并根据此变量是否为null来定义XMLID属性的值:

from item in _documentRoot.Descendants("MyItems")
let idAttr = item.Attribute("id")
select new MyClass
{
    XMLID = idAttr != null ? idAttr.Value : string.Empty
}).ToList<MyClass>();
Run Code Online (Sandbox Code Playgroud)