在将此XElement添加到匿名对象之前,如何检查此XElement是否为空?

我正在从XML文件填充匿名对象。 到现在为止,

commentary.Elements("Commentator")

总是有一个值,所以我从来没有检查过null。 我不得不删除它,现在它在尝试读取该行时失败了。

我正在查看代码,但我不知道要改变什么,因为它被选择为匿名对象的属性。

 var genericOfflineFactsheet = new { Commentary = (from commentary in doc.Elements("Commentary") select new { CommentaryPage = (string)commentary.Attribute("page"), BusinessName = (string)commentary.Attribute("businessName"), Commentator = (from commentator in commentary.Elements("Commentator") select new CommentatorPanel // ASP.NET UserControl { CommentatorName = (string)commentator.Attribute("name"), CommentatorTitle = (string)commentator.Attribute("title"), CommentatorCompany = (string)commentator.Attribute("company") }).FirstOrDefault() }).FirstOrDefault() 

问题是,我无法完全删除该行,因为有时候commentary.Elements("Commentator") 确实有一个值。 我确定此问题已经处理过,但我看不清楚该做什么。 有任何想法吗?

只需添加一个空检查。 (下面的代码应该是一个很好的测试者。有一个有一个没有评论员)

 XDocument doc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XComment("Example"), new XElement("Commentarys", new XElement("Commentary", new XAttribute("page", "2"), new XAttribute("businessName", "name"), new XElement("Commentator", new XAttribute("name", "name"), new XAttribute("title", "title") ) ) , new XElement("Commentary", new XAttribute("page", "3"), new XAttribute("businessName", "name2") ) ) ); var genericOfflineFactsheet = new { Commentary = ( from commentary in doc.Elements() .First().Elements("Commentary") select new { CommentaryPage = (string)commentary.Attribute("page"), BusinessName = (string)commentary.Attribute("businessName"), Commentator = (from commentator in commentary.Elements("Commentator") where commentator != null //<-----you need to add this line select new // ASP.NET UserControl { CommentatorName = (string)commentator.Attribute("name"), CommentatorTitle = (string)commentator.Attribute("title"), CommentatorCompany = (string)commentator.Attribute("company") } ).FirstOrDefault() } ).FirstOrDefault() }; 

未经测试…

怎么样的:

  XElement xe = doc.Elements("Commentary").FirstOrDefault(); Commentary = xe == null ? null : select new { ....snip.... 

这是我可能会考虑??的情况。 (合并)运营商。

 null ?? x --> x 

在这种情况下,你可以通过合并到一个空的Enumerable来逃脱。

我用 ? 运算符这样可以防止生成XMLElement:

  • 如果我使用的对象不为null,我在数组中返回一个新的XElement
  • 如果为null,则返回Enumerable.Empty

例:

 var xml = new XElement("Root", myobject == null ? Enumerable.Empty() : <= empty IEnumerable if it is null new [] <= a array with a XElement { new XElement("myobject", new XAttribute("Name", myobject.Name), new XAttribute("Type", myobject.Type) ...) }, ...); 

在这种情况下,如果创建的对象为null,则不会生成XElement。