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

1
3
8/2/2018 12:30:33 PM

Accepted Answer

You can use last() as index

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

Be sure to wrap the expression in parenthesis.

2
8/2/2018 12:58:05 PM

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'])]


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow