问题
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