【问题标题】:How can i check if this XElement is not null before adding it to an anonymous object?在将其添加到匿名对象之前,如何检查此 XElement 是否不为空?
【发布时间】:2010-10-12 21:03:19
【问题描述】:

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

commentary.Elements("Commentator")

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

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

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") 确实 有一个值。我确定这个问题之前已经处理过,但我不知道该怎么做。有什么想法吗?

【问题讨论】:

  • 当您说失败时,您是否收到 ObjRef 错误?
  • @Nix,这是一个 NullReferenceException
  • 不要重温过去,但我正在再次调查,您确定您的代码没有其他问题吗?我刚刚拿走了你的东西,并通过了一个 Commentary 为空的测试,它工作正常吗?
  • 不,我很确定就是这样 - 我按照您的建议应用了 where 子句并且它有效。我没有改变其他任何东西。

标签: c# linq-to-xml anonymous-types xelement


【解决方案1】:

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

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()
};

【讨论】:

    【解决方案2】:

    未经测试...

    怎么样:

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

    【讨论】:

      【解决方案3】:

      在这种情况下,我可能会考虑使用?? (coalesce) 运算符。

      null ?? x --> x
      

      在这种情况下,您可以通过合并到一个空的 Enumerable 来侥幸。

      【讨论】:

        【解决方案4】:

        我使用 ?操作员以这种方式防止生成 XMLElement:

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

        例子:

        var xml = new XElement("Root",
            myobject == null ? Enumerable.Empty<XElement>() : <= 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)
                                       ...)
                                   },
            ...);
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-21
          • 1970-01-01
          • 2013-10-02
          相关资源
          最近更新 更多