Count rows and columns in Html Table having subtables using HtmlAgilityPack

html-agility-pack html-table vb.net

Question

I need the number of columns and rows in order to parse an HTML table.

I tried using

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

However, if a table includes one or more subtables, I get the erroneous results.

I need to parse the following example of an HTML table:

<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>

I need the following outcomes from this sample: 3 columns, 5 rows

How can I count the rows and columns (just in the main table) without counting the rows and columns in the subtables?

1
1
3/3/2016 10:21:53 AM

Popular Answer

I came up with a solution in the following manner:

in columns:

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

In Rows:

Check for SubTables: First

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

Count the rows in the subtables, then deduct that number from the 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
1
3/3/2016 11:10:10 AM


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