我正在嘗試使用HTMLAgilityPack在每一行中獲取一些特定的單元格。
foreach (HtmlNode row in ContentNode.SelectNodes("descendant::tr"))
{
//Do something to first cell
//Do something to second cell
}
有更多的細胞,每個細胞需要一些專門的治療。我想有一種方法可以使用XPath來做到這一點,但我對此毫無用處。可能有類似的東西
var cell1 = row.SelectSingleNode("descendant::td:first");
要獲取每行的第一個單元格,您可以執行以下操作:
// from row
var firstCell = row.SelectSingleNode("td[1]");
// each first cell in a table (note: tbody is not always there)
var allFirstCells = table.SelectNodes("tbody/tr/td[1]");
換句話說,使用方括號和要選擇的單元格編號。一個例外是最後一個單元格,你可以使用last()
獲得如下:
// from row
var lastCell = row.SelectSingleNode("td[last()]");
// each last cell in a table
var allLastCells = table.SelectNodes("tbody/tr/td[last()]");
如果要將單元格放在當前單元格旁邊,可以執行以下操作:
// from row
var firstCell = row.SelectSingleNode("td[1]");
var siblingCell = firstCell.SelectSingleNode("./following-sibling::td");
您可能希望檢查null的返回值,這意味著您要么輸入錯誤,要么加載的DOM樹不包含您要求的單元格。