在 mscorlib.dll 中使用 doc.DocumentNode.SelectSingleNode 抛出异常 'System.ArgumentOutOfRangeException' 填充列表列表

Populating list of lists with doc.DocumentNode.SelectSingleNode throwing exception 'System.ArgumentOutOfRangeException' in mscorlib.dll

我有以下代码使用 C# WPF 表单,当我尝试访问标签[2][0] 时,该表单不断抛出异常。

List<List<string>> labels = doc.DocumentNode.SelectSingleNode("//table[@id='prod-att-table']")
                            .Descendants("tr")                                
                            .Select(tr => tr.Elements("th").Select(th => th.InnerText.Trim()).ToList())
                            .ToList();

我正在使用的 html 页面是这个 digikey 页面:http://www.digikey.com/product-detail/en/yageo/RC0402JR-0710KL/311-10KJRTR-ND/726418

查看页面源代码,我意识到 table "id='prod-att-table" 中的第三个 "tr" 后代实际上没有其他元素那样的 "th" 元素。我遇到的问题是我不知道如何让 labels[2][0] 不抛出异常。在我的代码中有没有一种方法可以跳过这个空元素而不将它添加到我的列表中?或者用空字符串 ""?

替换这些空值

如果您想避免空条目,您可以使用以下代码:

var list =  doc.DocumentNode.SelectSingleNode("//table[@id='prod-att-table']")
                .Descendants("tr")
                .Where(x=>x.Elements("th") != null && x.Elements("th").Count() != 0) //new Code
                .Select(tr => tr.Elements("th").Select(th => th.InnerText.Trim()).ToList())
                            .ToList();

获取物品的更好方法(至少在您提供的 link 上)是这样的:

var table = doc.DocumentNode.SelectSingleNode("//table[@id='prod-att-table']");
var nodes = table.SelectNodes(table.XPath + "//th").Select(x => x.InnerText.Trim()).ToList();

但请注意,这会给您 List<string> 而不是 List<List<string>>。不知道这是不是故意的。