获取每个 HTML 表格行的第一个和第二个单元格

发布于 2024-09-08 18:59:13 字数 364 浏览 6 评论 0原文

我试图使用 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");

I'm trying to get just some specific cells in each row using HTMLAgilityPack.

foreach (HtmlNode row in ContentNode.SelectNodes("descendant::tr"))
{
    //Do something to first cell
    //Do something to second cell
}

There are more cells, and each cell needs some specialized treatment. I guess there's a way to do this using XPath, but I'm fairly useless at that. Is there maybe something like

var cell1 = row.SelectSingleNode("descendant::td:first");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九局 2024-09-15 18:59:13

代替

descendant::tr

使用

descendant::tr/td[not(position() >2)]

Instead of:

descendant::tr

use:

descendant::tr/td[not(position() >2)]
半山落雨半山空 2024-09-15 18:59:13

要获取作为行子级的每个第一个单元格,您可以执行以下操作:

// 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 树不包含您要求的单元格。

To get each first cell that is a child of a row, you can do the following:

// 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]");

In other words, use square brackets and the cell-number you wish to select. An exception is the last cell, which you can get using last() as follows:

// from row
var lastCell = row.SelectSingleNode("td[last()]");

// each last cell in a table
var allLastCells = table.SelectNodes("tbody/tr/td[last()]");

If you want to get the cell next to a current cell, you can do something like this:

// from row
var firstCell = row.SelectSingleNode("td[1]");
var siblingCell = firstCell.SelectSingleNode("./following-sibling::td");

You may wish to check the return values for null, which means you either have a typo, or the DOM tree you loaded does not contain the cell you asked for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文