Roshni Gandhi Roshni Gandhi - 1 year ago 60
C# Question

LINQ to XML query does not read my XML file

I have created a project on Book Store and wanted to give Discounts. I have used XML file for that and tried to use LINQ query to retrieve data from that file every thing is okay but when I run the project it gives me an error NullReferenceException.
Here is the code of LINQ query.

string discountFilePath = HttpContext.Current.Server.MapPath("/App_Data/DiscountSettings.xml");
XDocument xmlDoc = XDocument.Load(discountFilePath);
IEnumerable<XElement> filteredDiscounts;
filteredDiscounts = from d in xmlDoc.Descendants("Discount")
where Convert.ToDateTime(d.Element("StartDate").Value) < DateTime.Now
&& Convert.ToDateTime(d.Element("EndDate").Value) >= DateTime.Now
select d;
XElement discountElement = filteredDiscounts.LastOrDefault();
string discounCategory = discountElement.Element("GenreName").Value;

And here is my xml file.

<?xml version="1.0" encoding="utf-8"?>

Please Help me with this

Answer Source


When You use LastOrDefault() method You must understood the method can return default value of object (default(XElement)) and can by null and You will need to chceck if value is null. For example for Your code:

if (discountElement != null)
  string discounCategory = discountElement.Element("GenreName").Value;

Exept this Your code is good. Problem is the XML file and value of StartDate an EndDate. Change that value of tags as You have the where condition like StartDat < DateTime.Now and EndDate >= DateTime.Now, for example like this (for today)



filteredDiscounts.LastOrDefault(); will not return null and all will by good.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download