Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
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.
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#:
HTMLDocument class.<body> through the Body property.TextContent property..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.
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#:
QuerySelectorAll() to collect matching elements.TextContent from each matched element. 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.
The best extraction method depends on whether you need all text, main content, or specific fields from the HTML document.
| Text extraction task | Recommended API | Notes |
|---|---|---|
| Extract all body text | document.Body and TextContent | Fast starting point for simple documents. |
| Extract main article text | QuerySelector("main") or QuerySelector("article") | Useful when navigation and footer text should be skipped. |
| Extract headings only | QuerySelectorAll("h1, h2, h3") | Good for outline checks, SEO audits, and content summaries. |
| Extract lists or repeated blocks | QuerySelectorAll("li") or a class selector | Use a specific parent container when a page has several lists. |
| Extract link text and URLs | QuerySelectorAll("a[href]") with TextContent and
GetAttribute("href") | Use when both anchor text and destination URLs matter. |
| Issue | Cause | Fix |
|---|---|---|
| Extracted text contains navigation or footer content | The 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 spaces | HTML indentation and nested inline elements create extra whitespace in TextContent. | Normalize whitespace before saving extracted text. |
| Important URLs are missing | TextContent returns link text, not the href attribute. | Extract links separately with QuerySelectorAll("a[href]") and read GetAttribute("href"). |
Text inserted with CSS content is missing | CSS-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 missing | The text is created by client-side scripts after page load. | Inspect the loaded DOM and make sure the required text exists before extraction. |
No. TextContent returns the text inside an element and its descendants. It does not include the markup tags themselves.
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.
Yes. After reading and normalizing text, use standard .NET file APIs such as File.WriteAllText() or File.WriteAllLines() to save the result.
QuerySelector() and QuerySelectorAll().The complete C# examples and data files are available in the Aspose.HTML for .NET GitHub repository.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.