Extract Text from HTML in C#

To extract text from HTML in C#, load the document with HTMLDocument, read the body text with the TextContent property, or use QuerySelector() and QuerySelectorAll() to extract text only from selected elements.

HTML text extraction is useful for search indexing, content migration, archiving, validation, summarization, reporting, and data analysis. Aspose.HTML for .NET lets you parse HTML as a DOM tree, select the content area you need, read text nodes, and save the extracted text to a .txt file or another storage target.

This article shows two common workflows: extracting all body text from an HTML document and extracting only selected text blocks such as headings, paragraphs, and list items.

Extract Body Text from HTML

Use the TextContent property when you need text without HTML tags. For full-page extraction, document.Body.TextContent is usually the simplest starting point. The Body property gives access to the document <body> element, and TextContent returns the text content of that element and its descendants.

The following example uses the source file extract-text-article.html, reads all text from the document body, and saves cleaned line-based text to a TXT file.

To extract body text from HTML in C#:

  1. Load the source HTML document with the HTMLDocument class.
  2. Access the document <body> through the Body property.
  3. Read the body text with the TextContent property.
  4. Remove empty lines and trim whitespace if the output should be easier to read.
  5. Save the extracted text to a .txt file.
 1using Aspose.Html;
 2using System;
 3using System.IO;
 4using System.Linq;
 5using System.Text;
 6
 7string inputPath = Path.Combine(DataDir, "extract-text-article.html");
 8string outputPath = Path.Combine(OutputDir, "article-text.txt");
 9
10using (HTMLDocument document = new HTMLDocument(inputPath))
11{
12    // Read body text and keep meaningful lines instead of collapsing everything.
13    string[] lines = document.Body.TextContent
14        .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
15        .Select(line => line.Trim())
16        .Where(line => line.Length > 0)
17        .ToArray();
18
19    // Save one text block per line.
20    File.WriteAllLines(outputPath, lines, Encoding.UTF8);
21    Console.WriteLine(string.Join(Environment.NewLine, lines));
22}

The example loads an HTML document, reads the text content of the <body> element, removes empty lines, trims whitespace, and writes each meaningful text line to article-text.txt. This workflow is suitable when the whole body is meaningful content.

Extract Text from Selected Elements

Many pages include navigation, footers, sidebars, scripts, or related links that should not be included in extracted content. In these cases, select a specific container or a set of elements before reading TextContent. The QuerySelectorAll(selector) method returns a NodeList of elements that match a CSS selector.

The following example uses extract-selected-content.html. The source document contains navigation and footer text, but the selector extracts only headings, paragraphs, and list items from the article content.

To extract selected HTML text in C#:

  1. Load the HTML document.
  2. Choose a CSS selector that matches the content you want to keep.
  3. Call QuerySelectorAll() to collect matching elements.
  4. Read TextContent from each matched element.
  5. Normalize and save each extracted text line.
 1using Aspose.Html;
 2using Aspose.Html.Collections;
 3using Aspose.Html.Dom;
 4using System;
 5using System.Collections.Generic;
 6using System.IO;
 7using System.Text;
 8
 9string inputPath = Path.Combine(DataDir, "extract-selected-content.html");
10string outputPath = Path.Combine(OutputDir, "selected-content.txt");
11
12using (HTMLDocument document = new HTMLDocument(inputPath))
13{
14    // Select only content elements inside the article.
15    NodeList nodes = document.QuerySelectorAll("article.content h1, article.content p, article.content li");
16    List<string> lines = new List<string>();
17
18    foreach (Element element in nodes)
19    {
20        string text = NormalizeText(element.TextContent);
21
22        if (!string.IsNullOrWhiteSpace(text))
23        {
24            lines.Add(text);
25        }
26    }
27
28    File.WriteAllLines(outputPath, lines, Encoding.UTF8);
29}
30
31static string NormalizeText(string value)
32{
33    if (string.IsNullOrWhiteSpace(value))
34    {
35        return string.Empty;
36    }
37
38    string[] parts = value.Split(new[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
39    return string.Join(" ", parts);
40}

The selector limits extraction to the article body and skips navigation and footer text. This is often better for SEO audits, content migration, and indexing pipelines because the output contains the main content rather than repeated page chrome.

Choose a Text Extraction Method

The best extraction method depends on whether you need all text, main content, or specific fields from the HTML document.

Text extraction taskRecommended APINotes
Extract all body textdocument.Body and TextContentFast starting point for simple documents.
Extract main article textQuerySelector("main") or QuerySelector("article")Useful when navigation and footer text should be skipped.
Extract headings onlyQuerySelectorAll("h1, h2, h3")Good for outline checks, SEO audits, and content summaries.
Extract lists or repeated blocksQuerySelectorAll("li") or a class selectorUse a specific parent container when a page has several lists.
Extract link text and URLsQuerySelectorAll("a[href]") with TextContent and GetAttribute("href")Use when both anchor text and destination URLs matter.

Common HTML Text Extraction Issues

IssueCauseFix
Extracted text contains navigation or footer contentThe extraction reads the whole body instead of the main content container.Use QuerySelector() or QuerySelectorAll() with a selector for main, article, or another stable content wrapper.
Output has too many line breaks or spacesHTML indentation and nested inline elements create extra whitespace in TextContent.Normalize whitespace before saving extracted text.
Important URLs are missingTextContent returns link text, not the href attribute.Extract links separately with QuerySelectorAll("a[href]") and read GetAttribute("href").
Text inserted with CSS content is missingCSS-generated content is created during styling and is not part of the document tree.Use TextContent for source HTML text. If generated text matters, inspect the CSS rules that define content or include that text in the source HTML.
Dynamically inserted text is missingThe text is created by client-side scripts after page load.Inspect the loaded DOM and make sure the required text exists before extraction.

FAQ

Does TextContent include HTML tags?

No. TextContent returns the text inside an element and its descendants. It does not include the markup tags themselves.

Should I extract text from the whole body or selected elements?

Use document.Body.TextContent for simple documents. Use CSS selectors when the page contains navigation, footers, sidebars, or repeated template text that should not be part of the extracted content.

Can I save extracted HTML text as a TXT file?

Yes. After reading and normalizing text, use standard .NET file APIs such as File.WriteAllText() or File.WriteAllLines() to save the result.

Related Data Extraction Articles

The complete C# examples and data files are available in the Aspose.HTML for .NET GitHub repository.