How to get the last table in xpath?

c# html-agility-pack xpath

Question

So I have the following situation:

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

as you can see I have two table with the same classes, I want get the last table (I cannot use index because the number of the table changing).

For the moment I have this code:

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

unfortunately I cannot find any .Last() method, maybe is possible do this directly with xpath so without use SelectNodes()?

Accepted Answer

You can use last() as index

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

Be sure to wrap the expression in parenthesis.


Popular Answer

last() will return you the last table only if both tables are children of the same parent. So if HTML really looks like

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

then

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

will fetch required table...

But in case

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

you might need

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


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why