I am new at using Linq to XML and have run across a rather troublesome error. When trying to pull in my XML file I get an error that reads “Object reference not set to an instance of an object.” and it is saying the error is because I am trying to use the select new statement. I have attached my code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XDocument feed = XDocument.Load(Server.MapPath("VEHICLES.XML"));
var query = from c in feed.Descendants("VEHICLES")
where (string) c.Element("VehicleType").Value == "0"
select new
{
Vin = c.Element("Vin").Value,
Status = c.Element("VehicleType").Value,
Year = c.Element("Year").Value
};
CarLister.DataSource = query;
CarLister.DataBind();
}
}
the code works fine pulling in the all of the nodes using select c; instead of selectnew, but ideally I would like to only select certain pieces of information and there are a few entries that I would need to modify when pulling them in. I am not really sure what is causing this issue so any pointers or ideas on how to fix it would be greatly Appreciated, if you need any other info just ask!
The problem is that you’re using the
Valueproperty everywhere – that will always fail if the result offoo.Element(...)returns null due to the element being missing. Fortunately, there’s a simple way round it – cast to string instead. TheXElementexplicit conversion tostringreturns null if the “input” is null, which is very handy.That will survive in the case that a
<VEHICLES>element doesn’t have a<VehicleType>,<Vin>,<Status>or<Year>child.However, if this failure actually means the data was invalid to start with, you may want an exception anyway. It depends on how much you’re relying on the data to be sane to start with.