Null reference exception in my LINQ to XML code

霸气de小男生 提交于 2019-12-11 07:29:30

问题


I have been playing around with linking XML files to dropdown lists and gridviews.

I have managed to populate one dropdown list from the XML document and then a gridview to another but when try to add a where clause, I get a null reference exception and not sure why. How can I resolve this?

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

回答1:


Avoid using .Value; a range of null-safe implicit conversion operators are available:

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



回答2:


Any of these:

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

could be null, and then calling .ToString() or .Value on them would give you the exception you're seeing.

If you're not happy to catch XML problems via NullReferenceExceptions, then you need to take the value of the Attribute() call into a local variable and then test against that (or call it twice and test the first call for null).




回答3:


Try: where c.Attribute("PropertyId") != null && c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString() for the condition part and c.Element("ThumbUrl") != null . Your code should look like this:

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


来源:https://stackoverflow.com/questions/5753430/null-reference-exception-in-my-linq-to-xml-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!