Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 避免读取提要中不存在的rss节点_C#_Linq_Rss - Fatal编程技术网

C# 避免读取提要中不存在的rss节点

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

我正在阅读一个rss提要,在大多数情况下,它在我的项目中都有“credit”节点。但在某些情况下,它不存在。如何避免获取对象未设置异常? 我使用c中的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;