Net Core MVC 6中LINQ读取XML时XAttribute空值警告消除方法
消除LINQ to XML中访问Attribute.Value的空引用警告
警告根源
编译器提示的警告,是因为直接调用r.Attribute("brandID").Value时,如果<tagline>节点没有brandID属性,r.Attribute("brandID")会返回null,此时访问.Value会触发空引用异常,编译器提前提示这个潜在风险。
解决方法
方法1:先检查属性存在性,再访问Value
使用let关键字提前获取属性,先判断属性不为null,再比较其Value:
var query = from XElement r in element.Descendants("tagline") let brandIdAttr = r.Attribute("brandID") where brandIdAttr != null && brandIdAttr.Value == siteId select r.Element("tagline2")?.Attribute("tagline2"); var aa = query.FirstOrDefault(); if (aa != null) footer = aa.Value;
方法2:利用XAttribute的隐式转换(推荐)
XAttribute支持隐式转换为string,当属性不存在时会自动返回null,无需直接访问.Value,写法更简洁:
var query = from XElement r in element.Descendants("tagline") where (string)r.Attribute("brandID") == siteId select r.Element("tagline2")?.Attribute("tagline2"); var aa = query.FirstOrDefault(); if (aa != null) footer = aa.Value;
方法3:简化后续取值逻辑(进阶)
可以直接在查询中获取tagline2的属性值,结合FirstOrDefault和空合并运算符,省去单独的if判断:
footer = (from XElement r in element.Descendants("tagline") where (string)r.Attribute("brandID") == siteId select (string)r.Element("tagline2")?.Attribute("tagline2")) .FirstOrDefault() ?? "";
这里如果没有匹配的节点或属性,footer会被设为空字符串,可根据需求调整默认值。
内容的提问来源于stack exchange,提问作者Diego
相关产品推荐
相关产品推荐

