LINQ to XML - 检查空值
本文关键字:检查 空值 XML to LINQ | 更新日期: 2023-09-27 18:31:49
我已经使用 LINQ 大约 2 天了,所以请耐心等待。
这是我当前的代码;
_resultList = (
from
item in _documentRoot.Descendants("MyItems")
select
new MyClass
{
XMLID = item.Attribute("id").Value
}).ToList<MyClass>();
大多数元素都有一个"id"属性,并且它们被成功添加到列表中。但是,有些没有"ID"。对于这些,我希望"id"只是一个空字符串。
在尝试访问该属性之前,如何检查该属性是否存在?谢谢
不需要将属性存储在其他变量中。如果属性不存在,则将属性转换为字符串将返回null
。使用空合并运算符的幂,您可以提供默认值 - 空字符串:
from item in _documentRoot.Descendants("MyItems")
select new MyClass {
XMLID = (string)item.Attribute("id") ?? ""
}
您可以将其存储在变量中,并根据此变量是否为 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>();