【问题标题】:Reading XML using XDocument & Linq - check if element is NULL?使用 XDocument 和 Linq 读取 XML - 检查元素是否为 NULL?
【发布时间】:2011-02-05 09:06:16
【问题描述】:

我正在使用 LINQ 和 XDocument 来读取 XML 文件。这是代码:

XDocument xml = XDocument.Load(filename);

var q = from b in xml.Descendants("product")
        select new
        {
            name = b.Element("name").Value,
            price = b.Element("price").Value,                    
            extra = b.Element("extra1").Value,
            deeplink = b.Element("deepLink").Value                   
        };

现在的问题是,extra1 字段并不总是存在。 XML 文件中有没有该节点的项目。如果发生这种情况,它会因 NullReferenceException 而崩溃。

是否有可能包含“检查是否为空”以便防止它崩溃?

【问题讨论】:

    标签: c# asp.net xml linq


    【解决方案1】:

    使用(string) 代替.Value

    var q = from b in xml.Descendants("product")
            select new
            {
                name = (string)b.Element("name"),
                price = (double?)b.Element("price"),                    
                extra = (string)b.Element("extra1"),
                deeplink = (string)b.Element("deepLink")                   
            };
    

    这也适用于other datatypes,包括许多可为空的类型,以防元素不总是存在。

    【讨论】:

      【解决方案2】:

      您可以使用“空合并”运算符:

      var q = from b in xml.Descendants("product")
              select new
              {
                  name = (string)b.Element("name") ?? "Default Name",
                  price = (double?)b.Element("price") ?? 0.0,                    
                  extra = (string)b.Element("extra1") ?? String.Empty,
                  deeplink = (string)b.Element("deepLink") ?? String.Empty                   
              };
      

      这样,您可以完全控制在没有元素时使用的默认值。

      【讨论】:

      • price 必须是 double? 才能使该行有意义。
      【解决方案3】:

      使用以下示例在使用该元素之前检查该元素是否存在。

      if( b.Elements("extra1").Any() )
      {
         extra = b.Element("extra1").Value;
      }
      

      【讨论】:

        【解决方案4】:

        这里是使用 XDocument 读取 XML 文件的示例。

          XDocument objBooksXML = XDocument.Load(Server.MapPath("books.xml"));
            var objBooks = from book in
                           objBooksXML.Descendants("Book")
                           select new { 
                                        Title = book.Element("Title").Value, 
                                        Pages = book.Element("Pages").Value 
                                      };
        
            Response.Write(String.Format("Total {0} books.", objBooks.Count()));
            gvBooks.DataSource = objBooks;
            gvBooks.DataBind();
        

        【讨论】:

        • 这段代码的问题是,如果“Book”不包含“Title”或“Pages”元素,当尝试从其中任何一个获取 .Value 时,您将抛出空异常。
        猜你喜欢
        • 2012-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多