【问题标题】:Null reference exception in my LINQ to XML code我的 LINQ to XML 代码中的空引用异常
【发布时间】:2011-04-22 07:56:36
【问题描述】:

我一直在尝试将 XML 文件链接到下拉列表和网格视图。

我已设法从 XML 文档填充一个下拉列表,然后将 gridview 填充到另一个,但是当尝试添加 where 子句时,我得到一个空引用异常并且不知道为什么。我该如何解决这个问题?

XDocument xmlDoc = XDocument.Load(Server.MapPath("XMLFile.xml"));
var q = from c in xmlDoc.Descendants("Images")
        where c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString()
        select new
        {
            PropertyID = c.Element("ThumbUrl").Value,
        };
GridView1.DataSource = q;
GridView1.DataBind();

【问题讨论】:

  • where 部分是否抛出空引用?您确定“Images”节点上存在“PropertyId”属性吗?
  • 好的,感谢您设法让它工作到一个非常感谢的地步 - 如果你能提供帮助,最后一个问题....hte gridview 现在在下拉框更改时显示正确的 ThumbUrl - 但是怎么做我将 gridview 更改为链接到图像而不是仅显示 url?
  • Kev - 要充分利用 StackOverflow,您需要投票/接受对您有帮助的答案,如果您将第二个问题发布在它自己的权利,而不是在评论中。

标签: c# xml linq linq-to-xml nullreferenceexception


【解决方案1】:

避免使用.Value;可以使用一系列 null 安全的隐式转换运算符:

var q = from c in xmlDoc.Descendants("Images")
        where (string)c.Attribute("PropertyId")
               == DropDownList1.SelectedValue.ToString()
        select new
        {
            PropertyID = (string)c.Element("ThumbUrl"),
        };

【讨论】:

  • 这值得更多的认可
【解决方案2】:

其中任何一个:

c.Attribute("PropertyId")
c.Element("ThumbUrl")
DropDownList1.SelectedValue

可能为空,然后在它们上调用 .ToString() 或 .Value 会给你看到的异常。

如果您不乐意通过 NullReferenceExceptions 捕获 XML 问题,那么您需要将 Attribute() 调用的值放入一个局部变量中,然后对其进行测试(或调用两次并测试第一次调用是否为 null )。

【讨论】:

    【解决方案3】:

    尝试: where c.Attribute("PropertyId") != null && c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString() 用于条件部分和 c.Element("ThumbUrl") != null 。您的代码应如下所示:

    XDocument xmlDoc = XDocument.Load(Server.MapPath("XMLFile.xml"));
    var q = from c in xmlDoc.Descendants("Images")
            where c.Attribute("PropertyId") != null 
            && c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString() 
            && c.Element("ThumbUrl") != null
            select new
            {
                PropertyID = c.Element("ThumbUrl").Value,
            };
    GridView1.DataSource = q;
    GridView1.DataBind();
    

    【讨论】:

      【解决方案4】:
      from x in document.Descendants("Images")
      let xElement = x.Element("PropertyId")
      where xElement != null && xElement.Value == DropDownList1.SelectedValue.ToString()
      select new
      {
         PropertyID = c.Element("ThumbUrl").Value,
      };
      

      【讨论】:

        猜你喜欢
        • 2012-02-07
        • 1970-01-01
        • 2011-07-22
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多