[英]Reading XML using XDocument & Linq - check if element is NULL?
[英]LINQ to XML - check for null?
我已经使用LINQ大约2天了,所以请多多包涵。
这是我当前的代码;
_resultList = (
from
item in _documentRoot.Descendants("MyItems")
select
new MyClass
{
XMLID = item.Attribute("id").Value
}).ToList<MyClass>();
大多数元素具有'id'属性,并且已成功将它们添加到列表中。 但是,有些没有“ id”。 对于这些,我希望“ id”只是一个空字符串。
在尝试访问属性之前,如何检查该属性是否存在? 谢谢
您无需将属性存储在其他变量中。 如果属性不存在,则将属性转换为字符串将返回null
。 使用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>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.