I have a large number of records (about 2,000) returned as XML and I am using a LINQ statement to parse the XML and return a collection objects. I am however, getting an exception when the LINQ expressions evaluates.
object reference not set to an instance of an object
I know that somewhere the LINQ expression is trying to deal with a value that is null
or missing. Is there a way that the exception or stack trace could tell me where in the XML this might be happening as I am dealing with a lot of XML.
Here is my LINQ query ...
XDocument xml = XDocument.Parse(responseXml);
List<PaymentModel> paymentDetails = xml.Descendants("CustomerPayment")
.Select(x => new PaymentModel
{
PaymentRecordNumber = x.Element("InvoiceId").Value.ToString(),
PaymentMade = (decimal)x.Element("PaymentMade"),
PaymentDate = !string.IsNullOrEmpty(x.Element("PaymentDate").Value.ToString()) ? (DateTime)x.Element("PaymentDate") : DateTime.MinValue,
InvoiceCollection = x.Elements("CustomerInvoices")
.Where(
i => i.Element("InvoiceId").Value.Contains("USA")
|| i.Element("InvoiceId").Value.Contains("JAPAN")
|| i.Element("InvoiceId").Value.Contains("UK")
|| i.Element("InvoiceId").Value.Contains("DENMARK")
)
.Select(i => new InvoiceModel()
{
InvoiceNumber = i.Element("InvoiceNumber").Value.ToString(),
InvoiceAmount = (decimal)i.Element("AmountPaid")
}).ToList< InvoiceModel>()
}).ToList<PaymentModel>();