我有大量的记录(大约2,000个)作为XML返回,我使用LINQ语句来解析XML并返回一个集合对象。但是,当LINQ表达式求值时,我得到一个异常。
object reference not set to an instance of an object
我知道LINQ表达式正在尝试处理null
或缺少的值。有没有办法让异常或堆栈跟踪可以告诉我在处理大量XML时XML中可能发生的情况。
这是我的LINQ查询...
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>();
答案 0 :(得分:1)
如果您只想避免异常,可以使用C#的空运算符来检查值是null
内联,并在需要时指定默认值。
您的代码需要如下所示:
List<PaymentModel> paymentDetails = xml.Descendants("CustomerPayment")
.Select(x => new PaymentModel
{
PaymentRecordNumber = x.Element("InvoiceId")?.Value.ToString() ?? String.Empty,
PaymentMade = Convert.ToDecimal(x.Element("PaymentMade")?.Value ?? "0"),
PaymentDate = !string.IsNullOrEmpty(x.Element("PaymentDate")?.Value.ToString() ?? String.Empty) ? Convert.ToDateTime(x.Element("PaymentDate")?.Value): DateTime.MinValue,
InvoiceCollection = x.Elements("CustomerInvoices")?
.Where(
i => (bool)i.Element("InvoiceId")?.Value.Contains("USA")
|| (bool)i.Element("InvoiceId")?.Value.Contains("JAPAN")
|| (bool)i.Element("InvoiceId")?.Value.Contains("UK")
|| (bool)i.Element("InvoiceId")?.Value.Contains("DENMARK")
)
.Select(i => new InvoiceModel()
{
InvoiceNumber = i.Element("InvoiceNumber")?.Value.ToString() ?? String.Empty,
InvoiceAmount = Convert.ToDecimal(i.Element("AmountPaid")?.Value ?? "0")
}).ToList<InvoiceModel>()
}).ToList<PaymentModel>();
如果要在XML中查找错误,可以拆分文件以缩小导致异常的部分,或逐行注释掉查询以至少找到元素的名称。
另一种方法是通过使用XSD验证文档是否有效,该write the XSD by hand描述了XML的结构。它可以帮助找到不存在元素或属性的位置或存在不需要的元素和属性的位置。您可以generate it from C# classes甚至。