【问题标题】: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()]"
请务必将表达式括在括号中。