3

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()?

Charanoglu
  • 1,229
  • 2
  • 11
  • 30
  • Possible duplicate of [XPath for elements using Chrome?](https://stackoverflow.com/questions/39864280/xpath-for-elements-using-chrome) – mjwills Aug 02 '18 at 12:33
  • 1
    Possible duplicate of [XSLT getting last element](https://stackoverflow.com/questions/1459132/xslt-getting-last-element) – Caramiriel Aug 02 '18 at 13:12

2 Answers2

4

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'])]
Andersson
  • 51,635
  • 17
  • 77
  • 129
2

You can use last() as index

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

Be sure to wrap the expression in parenthesis.

Guy
  • 46,488
  • 10
  • 44
  • 88