将 XML 文档转换为导致异常的对象列表的 LINQ 查询

LINQ query which converts XML document to object list causing exception

我有一个非常大的 LINQ 查询,它将 XML 个节点读取到对象属性中,但是我的查询中的一行导致 System.FormatException 异常基于 "Input string not in a correct format".

DeliveryFee = x.Descendants("LineItemShipping").Select(e => (double)e.Element("TotalPrice")).FirstOrDefault(),

(double)e.Element("TotalPrice") // this text in the line is highlighted by the debugger so this element must be the cause

XML 文档中有 1000 条记录,所以我无法找到导致异常的记录,有没有办法可以 "throw" 捕获导致错误的值( ) 陈述?我不确定如何调试 LINQ 查询以在运行时获取值,我确定这只是一个问题,因为 XML 节点对于此特定记录为空。 (或包含非法字符)

我知道这是一个特定的记录,因为我可以毫无问题地提取许多行,但是当我尝试提取一个特定的子集时,我得到了异常,所以我知道它被本地化为一个月的数据,但我我无法进一步缩小范围。

您可以在 select 表达式中添加一个 try catch 语句,如下所示:

    var DeliveryFee = x.Descendants("LineItemShipping").
        Select(e => {
            try
            {
                var item = (double)e.Element("TotalPrice");  
                return item;
            }
            catch(Exception ex)
            {
                //This is just so it will compile and have a return value                        
                return double.MinValue;
            }                  
        }).
        FirstOrDefault();

要找到此错误,请先通过 Debug -> Exceptions 启用 breaking when an exception is thrown in visual studio。在 all 异常上启用中断,或在 System.FormatException.

上启用中断

现在 Visual Studio 将在为具有无效 TotalPriceLineItemShipping 节点抛出异常时停止。然后,在 immediate window, you can use the AncestorsAndSelf() 方法中通过键入以下内容找到有问题的节点:

e.Element("SomeStatus").AncestorsAndSelf().ToArray()

Visual Studio 将向您显示生成异常的 XElement 的路径。这应该可以让您找到有问题的 XML 节点。

尝试将 (double) 更改为 (double?) 以处理空情况,并尝试将 ?? 0 更改为零:

(double)(x.Descendants("LineItemShipping")
          .Select(e => (double?)e.Element("TotalPrice")).FirstOrDefault()) 
          ?? 0)