如何使用linq查询xml元素该元素是否存在C#

如何使用linq查询xml元素该元素是否存在C#,c#,wpf,linq,C#,Wpf,Linq,我试图从本地机器上循环使用相同格式的几个XML文件,但有些文件缺少元素,即图像。当循环到达一个缺少元素的文件时,程序在“选择新”时崩溃 XML: 我想是因为演员太难了吧 尝试使用保存强制转换和null条件运算符(?),这将防止出现NullreferenceExceptions: XDocument document = XDocument.Load(file); var nodes = from b in document.Descendants("node") let

我试图从本地机器上循环使用相同格式的几个XML文件,但有些文件缺少元素,即图像。当循环到达一个缺少元素的文件时,程序在“选择新”时崩溃

XML:


我想是因为演员太难了吧

尝试使用保存强制转换和null条件运算符(?),这将防止出现
NullreferenceExceptions

XDocument document = XDocument.Load(file);
var nodes = from b in document.Descendants("node")
            let imgs = b.Element("image")
            select new
            {
                ID = b.Element("id")?.Value as string,
                Title = b.Element("title")?.Value as string,
                StreetName = b.Element("body")?.Element("und")?.Element("n0")?.Element("value")?.Value as string,
                Images = imgs?.Descendants("und")?.ToList()
            };
XDocument document = XDocument.Load(file);
var nodes = from b in document.Descendants("node")
            let imgs = b.Element("image")
            select new
            {
                ID = (string)b.Element("id").Value,
                Title = (string)b.Element("title").Value,
                StreetName = (string)b.Element("body").Element("und").Element("n0").Element("value").Value,
                Images = imgs.Descendants("und").ToList()
            };
XDocument document = XDocument.Load(file);
var nodes = from b in document.Descendants("node")
            let imgs = b.Element("image")
            select new
            {
                ID = b.Element("id")?.Value as string,
                Title = b.Element("title")?.Value as string,
                StreetName = b.Element("body")?.Element("und")?.Element("n0")?.Element("value")?.Value as string,
                Images = imgs?.Descendants("und")?.ToList()
            };