【问题标题】:How to get the last table in xpath?如何获取 xpath 中的最后一个表?
【发布时间】:2019-01-10 05:32:45
【问题描述】:

所以我有以下情况:

<table class="table-main detail-odds sortable">
  ..
</table>
<table class="table-main detail-odds sortable">
  ..
</table>

如您所见,我有两个具有相同类的表,我想获得最后一个表(我不能使用索引,因为表的数量在变化)。

目前我有这个代码:

HtmlNode oddsTable = doc.DocumentNode
         .SelectNodes("//table[@class='table-main detail-odds sortable']");

不幸的是,我找不到任何.Last() 方法,也许可以直接使用xpath 执行此操作,所以不使用SelectNodes()

【问题讨论】:

标签: c# xpath html-agility-pack


【解决方案1】:

last() 仅当两个表都是同一父级的子级时,才会返回最后一个表。所以如果 HTML 真的看起来像

<table class="table-main detail-odds sortable">
  ..
</table>
<table class="table-main detail-odds sortable">
  ..
</table>

然后

//table[@class='table-main detail-odds sortable'][last()]

将获取所需的表...

万一

<div>
    <table class="table-main detail-odds sortable">
  ..
    </table>
</div>
<div>
    <table class="table-main detail-odds sortable">
  ..
    </table>
</div>

你可能需要

(//table[@class='table-main detail-odds sortable'])[count(//table[@class='table-main detail-odds sortable'])]

【讨论】:

  • 也谢谢你的回答:)
【解决方案2】:

您可以使用last() 作为索引

"(//table[@class='table-main detail-odds sortable'])[last()]"

请务必将表达式括在括号中。

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 2010-10-30
    相关资源
    最近更新 更多