Parse HTML Table Data with a .NET API
Aspose.HTML for .NET
loads an HTML file into an
HTMLDocument
so a C# application can query its DOM and extract structured table content. Select the required <table>, iterate through its rows, read both <th> and <td> cells, and pass the collected values to JSON, CSV, a database, or another application workflow.
Extract an HTML Table to JSON in C#
The following example selects the first table in input.html, preserves the order of header and data cells, and writes the extracted values to table-data.json. Use a more specific selector when the document contains several tables.
C# Code to Extract HTML Table Data
using Aspose.Html;
using Aspose.Html.Dom;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
string inputPath = "input.html";
string outputPath = "table-data.json";
using HTMLDocument document = new HTMLDocument(inputPath);
// Select the table to extract
Element table = document.QuerySelector("table");
if (table == null)
{
throw new InvalidOperationException("The HTML document does not contain a table.");
}
List<List<string>> tableData = new List<List<string>>();
// Read header and data cells in document order
foreach (Element row in table.QuerySelectorAll("tr"))
{
List<string> values = new List<string>();
foreach (Element cell in row.QuerySelectorAll("th, td"))
{
values.Add(cell.TextContent.Trim());
}
if (values.Count > 0)
{
tableData.Add(values);
}
}
JsonSerializerOptions options = new JsonSerializerOptions
{
WriteIndented = true
};
string json = JsonSerializer.Serialize(tableData, options);
File.WriteAllText(outputPath, json);
Steps to Extract Data from an HTML Table
- Load the source file with an
HTMLDocumentconstructor. - Select the required table with
QuerySelector(). An ID or class selector is safer thantablewhen the document contains several tables. - Use
QuerySelectorAll()to collect the table rows and then the<th>and<td>cells in each row. - Read and normalize each cell’s
TextContent, preserving the source row and column order. - Serialize the collected values with
JsonSerializerand save the resulting JSON file.
HTML Table Extraction Options and Limitations
- Select the correct table. Use
#id,.class,main table, or another stable CSS selector instead of assuming the first table is the required one. For more selection patterns, see CSS Selector and XPath Query . - Process one or many tables. Replace
QuerySelector()withQuerySelectorAll("table")when the application must extract every table from the document. - Control the row scope. The
trselector reads rows from<thead>,<tbody>, and<tfoot>. Narrow it when the output should omit a footer or process table sections separately. - Account for nested tables. A descendant selector can also reach rows inside a nested table. Use selectors tied to the required table structure when nested tables must be treated as separate datasets.
- Choose the destination format. The DOM API provides the extracted values; standard .NET serializers and file APIs can then write JSON, CSV, text, or application-specific records.
HTML Table Extraction Documentation
See Extract HTML Tables in C# for examples that read local files and web page URLs, preserve header cells, extract links, and write table values to CSV or text. The Data Extraction section also covers DOM navigation, CSS selectors, XPath, and extracting other types of content from web pages.
Get Started with Aspose.HTML for .NET API
Install Aspose.HTML for .NET from NuGet with the .NET CLI:
dotnet add package Aspose.HTML
You can also use the NuGet Package Manager UI or run Install-Package Aspose.HTML in the Package Manager Console. See the
installation guide
for setup details, or request a
temporary license
to evaluate the API without evaluation limitations.
HTML Table Data Extraction FAQ
1. How do I include table headers in the extracted data?
Read both <th> and <td> elements for every row. The example uses the selector th, td, so header values remain in their original position instead of being omitted from the JSON result.
2. Are empty HTML table cells retained in the JSON result?
Yes. Each selected <th> or <td> produces one string value, and an empty cell becomes an empty string after TextContent.Trim(). This retains the cell position within that row.
3. Can the extracted HTML table data be saved as CSV or Excel?
The DOM workflow returns cell values rather than imposing an output format. Write them as CSV with standard .NET file APIs, serialize them as JSON, or pass them to the spreadsheet component used by your application when an Excel workbook is required.
4. Does the extraction code expand rowspan and colspan automatically?
No. The attributes remain available on their table cells, but a flat list does not represent occupied grid positions. Add normalization logic when the output must expand spanning cells into a rectangular dataset.
5. Can I extract links or HTML markup from table cells instead of plain text?
Yes. TextContent returns cell text only. Use InnerHTML to retain nested markup, or select <a> elements inside each cell and read both their text and href attributes when link targets are required.
Related HTML Table Workflows
Create or edit tables, or extract tables with their markup, using focused Aspose.HTML for .NET guides.