C# 避免读取提要中不存在的rss节点
我正在阅读一个rss提要,在大多数情况下,它在我的项目中都有“credit”节点。但在某些情况下,它不存在。如何避免获取对象未设置异常? 我使用c中的linq以这种方式阅读它#C# 避免读取提要中不存在的rss节点,c#,linq,rss,C#,Linq,Rss,我正在阅读一个rss提要,在大多数情况下,它在我的项目中都有“credit”节点。但在某些情况下,它不存在。如何避免获取对象未设置异常? 我使用c中的linq以这种方式阅读它# 在检索元素值之前,应检查元素是否不为null: var creditElement = item.Element(media + "credit"); Credit = (creditElement == null) ? string.Empty : (string)creditElement.Value; 但Linq
在检索元素值之前,应检查元素是否不为null:
var creditElement = item.Element(media + "credit");
Credit = (creditElement == null) ? string.Empty : (string)creditElement.Value;
但Linq足够聪明——它可以显式地将元素值转换为字符串,并将缺少的元素视为null。所以您可以将元素转换为字符串,并使用null合并运算符指定默认值:
Credit = (string)item.Element(media + "credit") ?? String.Empty;
Credit = (string)item.Element(media + "credit") ?? String.Empty;