簡體   English   中英

我的LINQ to XML代碼中的空引用異常

[英]Null reference exception in my LINQ to XML code

我一直在嘗試將XML文件鏈接到下拉列表和gridviews。

我設法從XML文檔中填充一個下拉列表,然后填充到另一個網格視圖,但是當嘗試添加where子句時,我得到了null引用異常,並且不確定為什么。 我該如何解決?

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

避免使用.Value ; 提供了一系列空安全隱式轉換運算符:

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

以下任何一項:

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

可以為null,然后在它們上調用.ToString()或.Value將給您所看到的異常。

如果您不願意通過NullReferenceExceptions來捕獲XML問題,則需要將Attribute()調用的值放入本地變量,然后對該變量進行測試(或對其進行兩次調用,並在第一個調用中測試null)。

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,
};

試試: 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM