Count rows and columns in Html Table having subtables using HtmlAgilityPack

html-agility-pack html-table vb.net

Question

I'm parsing an Html table and I need the columns and rows count.

I tryed using:

ColNum = mTables(1).SelectNodes(".//th").Count
RowNum = mTables(1).SelectNodes(".//tr").Count

But I get a wrong results if table has one or more subtables.

Here's a sample of html table I need to parse:

<table border='1'>
    <tbody>
        <tr><th>Some Text</th><th>Some Text</th><th>Some Text</th></tr>
        <tr><td>Some data</td><td>Some data</td><td>Some data</td></tr>
        <tr><td>Some data</td><td>Some data
                     <table border='1'>
                         <tbody>
                             <tr><th>Some Text</th><th>Some Text</th></tr>
                             <tr><td>Some Data</td><td>Some Data</td></tr>
                         </tbody>
                     </table><td>Some data</td></tr>
        <tr><td>Some data</td><td>Some data</td><td>Some data</td></tr>
        <tr><td>Some data</td><td>Some data</td><td>Some data</td></tr>
    </tbody>
</table>

In this sample I need this results: Columns = 3 Rows = 5

How can I get the number of the rows and columns (only for the main table) without counting the subtable rows and columns?

Popular Answer

I solved this way:

For columns:

ColNum = mTables(1).SelectSingleNode(".//tbody//tr[1]").SelectNodes(".//th").Count

For Rows:

First: Check for SubTables

Dim SubTbl%
Try
    SubTbl% = mTables(1).SelectNodes(".//table").Count
Catch ex As Exception
    SubTbl% = 0
End Try

Then: Count Rows in Subtables and subtract from total rows

Dim SubTRows% = 0
If SubTables > 0 Then
    For SubT As Short = 1 To SubTables
        Dim STRows% = mTables(1).SelectNodes(".//table[" & SubT & "]//tr").Count
        SubTRows += STRows
    Next
    RowsNum = mTables(1).SelectNodes(".//tr").Count - SubTRows
Else
    RowsNum = mTables(1).SelectNodes(".//tr").Count
End If



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