Parsing HTML
suggest changeParsing HTML comes up when you scrape data from a web page, extract links or text from a document, clean up user-submitted markup or rewrite HTML before serving it. Unlike XML, real-world HTML is rarely well formed: tags aren't closed, attributes aren't quoted, elements are nested wrongly. Browsers handle all that with a precisely specified algorithm from the HTML5 standard, and you want a parser that does the same.
.NET has no HTML parser in the base library. XDocument and XmlDocument (see LINQ to XML) reject most HTML found on the web. The two common NuGet packages are:
- AngleSharp: an HTML5-compliant parser that builds a W3C DOM, the same one browsers expose to JavaScript, with
QuerySelector,TextContent,ClassListand so on. This is the recommended choice for new code. - HtmlAgilityPack (HAP): an older, lenient parser with its own DOM and XPath queries. It's very widely used and still maintained.
Examples use C# 14 / .NET 10 and run as file-based programs (dotnet run app.cs). The #:package line pulls in the NuGet package.
Why not regular expressions
It's tempting to grab links with a regex:
using System.Text.RegularExpressions;
string html = """
<a href="/one">One</a>
<a class="x" href='/two'>Two</a>
<A HREF="/three" >Three</A>
<!-- <a href="/commented-out">Old</a> -->
<a href="/four?a=1&b=2">Four</a>
""";
foreach (Match m in Regex.Matches(html, "<a href=\"(.*?)\">"))
Console.WriteLine(m.Groups[1].Value);
/one
/commented-out
/four?a=1&b=2
The regex misses a link with single quotes, one with a different attribute order and one with uppercase tags. It matches a link inside a comment, and it returns & instead of &. A regex can work for a one-off job on HTML you control. For anything else use a parser.
Parsing a document with AngleSharp
HtmlParser.ParseDocument turns a string (or a Stream) into an IHtmlDocument. You navigate it with CSS selectors, exactly like document.querySelector in a browser:
#:package AngleSharp@1.8.5
using AngleSharp.Html.Parser;
string html = """
<html>
<head><title>Store & More</title></head>
<body>
<h1 id="top">Products</h1>
<ul class="products">
<li class="product" data-sku="A1"><a href="/p/a1">Widget</a> <span class="price">$9.99</span></li>
<li class="product sale" data-sku="B2"><a href="/p/b2">Gadget</a> <span class="price">$19.50</span></li>
<li class="product" data-sku="C3"><a href="https://other.example/c3">Gizmo</a> <span class="price">$5.00</span></li>
</ul>
</body>
</html>
""";
var parser = new HtmlParser();
var doc = parser.ParseDocument(html);
Console.WriteLine(doc.Title);
Console.WriteLine(doc.GetElementById("top")?.TextContent);
foreach (var li in doc.QuerySelectorAll("ul.products > li.product"))
{
string sku = li.GetAttribute("data-sku") ?? "";
string name = li.QuerySelector("a")!.TextContent;
string price = li.QuerySelector(".price")!.TextContent;
bool onSale = li.ClassList.Contains("sale");
Console.WriteLine($"{sku} {name,-7} {price,7}{(onSale ? " (sale)" : "")}");
}
Console.WriteLine(doc.QuerySelector("li.sale a")?.GetAttribute("href"));
Console.WriteLine(doc.QuerySelector("table") is null);
Store & More
Products
A1 Widget $9.99
B2 Gadget $19.50 (sale)
C3 Gizmo $5.00
/p/b2
True
The most used members:
QuerySelector(selector)returns the first matchingIElementornull.QuerySelectorAll(selector)returns all matches (an empty collection, nevernull).GetElementById,GetElementsByTagNameandGetElementsByClassNameare the classic DOM lookups.TextContentis the text of the element and all its descendants, with entities like&already decoded.GetAttribute(name)returns the raw attribute value ornull.HasAttribute,SetAttributeandRemoveAttributedo what their names say.ClassListis the set of CSS classes,Childrenthe child elements,ParentElementthe parent.
Every selector the browser supports works: div > p, a[href^='https'], li:nth-child(2), input:not([type=hidden]), h2 + p, tr:first-child td. Calling QuerySelector on an element searches only inside that element, which is how the loop above reads the name and price of each product.
Typed elements and resolving URLs
The DOM has specialized interfaces for many elements: IHtmlAnchorElement, IHtmlImageElement, IHtmlInputElement, IHtmlTableElement and so on. The generic QuerySelector<T> and QuerySelectorAll<T> extension methods from AngleSharp.Dom return them directly.
Typed properties also behave like the browser. IHtmlAnchorElement.Href is the absolute URL, resolved against the document's address. To give a document an address, load it through a BrowsingContext:
#:package AngleSharp@1.8.5
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
string html = """
<p>
<a href="/p/a1">Widget</a>
<a href="b2.html">Gadget</a>
<a href="https://other.example/c3">Gizmo</a>
<a href="#reviews">Reviews</a>
<a href="mailto:shop@example.com">Mail us</a>
<a>No href</a>
<img src="img/logo.png" alt="Logo">
</p>
""";
var context = BrowsingContext.New(Configuration.Default);
var doc = await context.OpenAsync(req => req
.Content(html)
.Address("https://shop.example/catalog/index.html"));
foreach (var a in doc.QuerySelectorAll<IHtmlAnchorElement>("a[href]"))
Console.WriteLine($"{a.TextContent,-8} {a.GetAttribute("href"),-26} -> {a.Href}");
var img = doc.QuerySelector<IHtmlImageElement>("img")!;
Console.WriteLine($"{img.AlternativeText}: {img.Source}");
Widget /p/a1 -> https://shop.example/p/a1
Gadget b2.html -> https://shop.example/catalog/b2.html
Gizmo https://other.example/c3 -> https://other.example/c3
Reviews #reviews -> https://shop.example/catalog/index.html#reviews
Mail us mailto:shop@example.com -> mailto:shop@example.com
Logo: https://shop.example/catalog/img/logo.png
a[href] skips the anchor without an href. GetAttribute returns what's in the markup, Href and Source return absolute URLs. When you crawl pages you almost always want the resolved one. A document from HtmlParser.ParseDocument has the address about:blank, so relative URLs can't be resolved. In that case combine them yourself with new Uri(baseUri, relative).
Extracting a table
IHtmlTableElement exposes Head, Bodies, Rows and Cells, which is easier than writing selectors for HTML tables:
#:package AngleSharp@1.8.5
using System.Globalization;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
string html = """
<table id="rates">
<thead><tr><th>Currency</th><th>Code</th><th>Rate</th></tr></thead>
<tbody>
<tr><td>Euro</td><td>EUR</td><td>1.0842</td></tr>
<tr><td>Pound sterling</td><td>GBP</td><td>1.2710</td></tr>
<tr><td>Japanese yen</td><td>JPY</td><td>0.0067</td></tr>
</tbody>
</table>
""";
var doc = new HtmlParser().ParseDocument(html);
var table = doc.QuerySelector<IHtmlTableElement>("#rates")!;
string[] headers = table.Head!.Rows[0].Cells.Select(c => c.TextContent.Trim()).ToArray();
Console.WriteLine(string.Join(" | ", headers));
var rates = new List<Rate>();
foreach (var row in table.Bodies[0].Rows)
{
string[] cells = row.Cells.Select(c => c.TextContent.Trim()).ToArray();
rates.Add(new Rate(cells[0], cells[1], decimal.Parse(cells[2], CultureInfo.InvariantCulture)));
}
foreach (var r in rates.OrderByDescending(r => r.Value))
Console.WriteLine(r);
record Rate(string Name, string Code, decimal Value);
Currency | Code | Rate
Rate { Name = Pound sterling, Code = GBP, Value = 1.2710 }
Rate { Name = Euro, Code = EUR, Value = 1.0842 }
Rate { Name = Japanese yen, Code = JPY, Value = 0.0067 }
Always Trim() cell text, since the markup usually contains whitespace and newlines around it. Parse numbers with CultureInfo.InvariantCulture when the page uses . as the decimal separator, otherwise the result depends on the machine's culture. For tables with rowspan or colspan you have to account for the spans yourself, because Cells returns only the cells physically present in the row.
How broken HTML is fixed
AngleSharp follows the HTML5 tree construction algorithm, so it produces the same tree as Chrome or Firefox no matter how broken the input is. It never throws on bad markup:
#:package AngleSharp@1.8.5
using AngleSharp.Html.Parser;
string html = "<title>Broken</title><p>One<p>Two <b>bold <i>both</b> italic?</i><table><td>cell</table><div>unclosed";
var parser = new HtmlParser();
var doc = parser.ParseDocument(html);
Console.WriteLine(doc.DocumentElement.OuterHtml);
Console.WriteLine(doc.QuerySelectorAll("p").Length);
<html><head><title>Broken</title></head><body><p>One</p><p>Two <b>bold <i>both</i></b><i> italic?</i><table><tbody><tr><td>cell</td></tr></tbody></table></p><div>unclosed</div></body></html>
2
The parser added the missing <html>, <head> and <body>, closed the first <p> when the second one started, fixed the misnested <b><i> by splitting the <i> into two, added <tbody> and <tr> to the table and closed the <div>.
The table ends up inside the second paragraph because the input has no <!DOCTYPE html>, so the document is in quirks mode, where <table> doesn't close an open <p>. With a doctype it does. This also shows how to pretty-print a tree with PrettyMarkupFormatter:
#:package AngleSharp@1.8.5
using AngleSharp;
using AngleSharp.Html;
using AngleSharp.Html.Parser;
var doc = new HtmlParser().ParseDocument("<!DOCTYPE html><p>Two<table><td>cell</table>");
Console.WriteLine(doc.Body!.InnerHtml);
Console.WriteLine(doc.Body!.ToHtml(new PrettyMarkupFormatter { Indentation = " " }));
<p>Two</p><table><tbody><tr><td>cell</td></tr></tbody></table>
<body>
<p>Two</p>
<table>
<tbody>
<tr>
<td>cell</td>
</tr>
</tbody>
</table>
</body>
This is why a selector that works in the browser's developer tools may fail on the HTML you downloaded, or the other way round: the browser shows the DOM after scripts ran and the parser fixed things up. Selectors like table > tr never match a parsed document, because the parser always inserts tbody. Use table tr instead.
Getting text and HTML out
TextContent, InnerHtml and OuterHtml give you the text, the markup inside an element and the markup including the element itself:
#:package AngleSharp@1.8.5
using AngleSharp.Html.Parser;
string html = """
<article>
<h2>Release notes</h2>
<p>Version <b>2.0</b> is out — see the <a href="/log">changelog</a>.</p>
<script>trackPageView();</script>
<style>p { color: red }</style>
<p>Fish & chips <3</p>
</article>
""";
var doc = new HtmlParser().ParseDocument(html);
var article = doc.QuerySelector("article")!;
var p = article.QuerySelector("p")!;
Console.WriteLine($"InnerHtml: {p.InnerHtml}");
Console.WriteLine($"TextContent: {p.TextContent}");
Console.WriteLine($"OuterHtml: {p.OuterHtml}");
Console.WriteLine(article.TextContent.Contains("trackPageView"));
foreach (var junk in article.QuerySelectorAll("script, style").ToList())
junk.Remove();
Console.WriteLine(article.TextContent.Contains("trackPageView"));
var paragraphs = article.QuerySelectorAll("h2, p")
.Select(e => string.Join(" ", e.TextContent.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)));
Console.WriteLine(string.Join("\n", paragraphs));
var last = article.QuerySelectorAll("p")[^1];
Console.WriteLine($"InnerHtml: {last.InnerHtml}");
InnerHtml: Version <b>2.0</b> is out — see the <a href="/log">changelog</a>.
TextContent: Version 2.0 is out — see the changelog.
OuterHtml: <p>Version <b>2.0</b> is out — see the <a href="/log">changelog</a>.</p>
True
False
Release notes
Version 2.0 is out — see the changelog.
Fish & chips <3
InnerHtml: Fish & chips <3
Some details worth knowing:
TextContentincludes the text of<script>and<style>elements, so remove them before extracting the text of a whole page.- It also keeps all the whitespace from the source. Splitting on whitespace and joining with a single space normalizes it.
- Entities are decoded:
—becomes—and becomes the non-breaking space U+00A0, not a regular space.char.IsWhiteSpacetreats it as whitespace, but comparing with' 'doesn't match it. InnerHtmlandOuterHtmlserialize the tree again, so they escape&,<and the non-breaking space. They don't return the original source text.
Modifying the DOM
The DOM is mutable. You can change attributes, remove and create elements, then serialize the result with OuterHtml or ToHtml():
#:package AngleSharp@1.8.5
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
string html = """
<div id="post">
<p>Read <a href="https://example.org/guide">the guide</a> or <a href="/faq">our FAQ</a>.</p>
<img src="cat.jpg">
<p class="ad">Buy now!</p>
</div>
""";
var doc = new HtmlParser().ParseDocument(html);
var post = doc.GetElementById("post")!;
// 1. external links open in a new tab
foreach (var a in post.QuerySelectorAll("a[href^='http']"))
{
a.SetAttribute("target", "_blank");
a.SetAttribute("rel", "noopener noreferrer");
}
// 2. lazy-load images and add a missing alt
foreach (var img in post.QuerySelectorAll<IHtmlImageElement>("img"))
{
img.SetAttribute("loading", "lazy");
if (!img.HasAttribute("alt")) img.AlternativeText = "";
}
// 3. drop ads
foreach (var ad in post.QuerySelectorAll(".ad").ToList())
ad.Remove();
// 4. append a new element
var footer = doc.CreateElement("p");
footer.ClassList.Add("note");
footer.TextContent = "Posted <today> & edited";
post.AppendChild(footer);
Console.WriteLine(post.OuterHtml);
<div id="post">
<p>Read <a href="https://example.org/guide" target="_blank" rel="noopener noreferrer">the guide</a> or <a href="/faq">our FAQ</a>.</p>
<img src="cat.jpg" loading="lazy" alt="">
<p class="note">Posted <today> & edited</p></div>
Setting TextContent escapes the text for you, so <today> can't inject markup. Assigning to InnerHtml parses the string as HTML, so only do that with trusted markup. Removing the ad left its surrounding whitespace text nodes behind, which is harmless for rendering.
Sanitizing untrusted HTML
If users can submit HTML (comments, rich-text editors, Markdown that allows HTML), you must remove scripts, event handlers and javascript: URLs before showing it to others. Don't write your own filter with a parser and a blacklist. There are too many tricks. The HtmlSanitizer package, built on AngleSharp, uses an allowlist of tags, attributes, CSS properties and URL schemes:
#:package HtmlSanitizer@9.2.1039
using Ganss.Xss;
string userInput = """
<p onclick="steal()">Hello <b>world</b>!</p>
<script>alert('xss')</script>
<a href="javascript:alert(1)">click</a>
<a href="https://example.com" style="position:fixed">ok link</a>
<img src=x onerror="alert(2)">
<iframe src="https://evil.example"></iframe>
""";
var sanitizer = new HtmlSanitizer();
Console.WriteLine(sanitizer.Sanitize(userInput));
var strict = new HtmlSanitizer();
strict.AllowedTags.Clear();
foreach (var t in new[] { "p", "b", "i", "a" }) strict.AllowedTags.Add(t);
strict.AllowedAttributes.Clear();
strict.AllowedAttributes.Add("href");
Console.WriteLine("---");
Console.WriteLine(strict.Sanitize(userInput));
<p>Hello <b>world</b>!</p>
<a>click</a>
<a href="https://example.com" style="position: fixed">ok link</a>
<img src="x">
---
<p>Hello <b>world</b>!</p>
<a>click</a>
<a href="https://example.com">ok link</a>
The default configuration removed the <script>, the <iframe>, the onclick and onerror handlers and the javascript: URL, but kept harmless formatting. The strict configuration keeps only the listed tags and attributes: <img> and style are gone. Configure the sanitizer once at startup and reuse it rather than building a new one for every request.
If you only need to show user text, not user HTML, don't parse anything. Encode it:
using System.Net;
using System.Text.Encodings.Web;
string name = "<script>alert('hi')</script> & \"friends\"";
Console.WriteLine(WebUtility.HtmlEncode(name));
Console.WriteLine(HtmlEncoder.Default.Encode(name));
Console.WriteLine(WebUtility.HtmlDecode("Fish & chips — © 2026 😀"));
<script>alert('hi')</script> & "friends"
<script>alert('hi')</script> & "friends"
Fish & chips — © 2026 😀
WebUtility.HtmlEncode and HtmlEncoder.Default both make text safe to put inside an element or a quoted attribute. ASP.NET Core Razor views encode with HtmlEncoder automatically. WebUtility.HtmlDecode is the reverse and handles named, decimal and hex entities. For text that came from a parsed document you don't need it, because TextContent is already decoded.
Downloading and parsing a page
To parse a page from the web, download it with HttpClient (see Performing HTTP requests) and pass the stream to the parser, or let AngleSharp download it:
#:package AngleSharp@1.8.5
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
// Option 1: HttpClient + HtmlParser
using var http = new HttpClient();
http.DefaultRequestHeaders.UserAgent.ParseAdd("MyScraper/1.0 (+https://example.com/bot)");
using var response = await http.GetAsync("https://example.com/");
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync();
var doc = await new HtmlParser().ParseDocumentAsync(stream);
Console.WriteLine($"{doc.Title} | charset: {doc.CharacterSet}");
// Option 2: let AngleSharp download the page
var config = Configuration.Default.WithDefaultLoader();
var context = BrowsingContext.New(config);
var doc2 = await context.OpenAsync("https://example.com/");
Console.WriteLine($"{doc2.StatusCode} {doc2.Url}");
Console.WriteLine(doc2.QuerySelector("p")?.TextContent[..40]);
Console.WriteLine(doc2.QuerySelector("script")?.GetAttribute("src"));
Example Domain | charset: utf-8
OK https://example.com/
This domain is for use in documentation
/s.js
Passing a Stream rather than a string lets the parser detect the encoding from <meta charset> or the byte order mark, which matters for pages that aren't UTF-8. WithDefaultLoader() enables HTTP requests inside AngleSharp. OpenAsync then sets the document's address, so Href resolves relative links, and follows redirects. Note that the HTML on example.com has unquoted attributes like lang=en, which is valid HTML5 and parsed fine.
Neither approach runs JavaScript. AngleSharp sees the HTML the server sent, nothing more. If a site renders its content with JavaScript, you'll find an empty <div id="root"> in the document. For such sites either look for the JSON API the page calls (in the browser's network tab) and use it directly, or drive a real browser with Microsoft.Playwright.
When scraping, set a descriptive User-Agent, respect robots.txt and the site's terms, cache what you download and don't send requests in a tight loop. Reuse a single HttpClient instead of creating one per request.
HtmlAgilityPack
HtmlAgilityPack has been around since 2006 and you'll find it in a lot of existing code. Its query language is XPath:
#:package HtmlAgilityPack@1.13.1
using HtmlAgilityPack;
string html = """
<ul class="products">
<li class="product" data-sku="A1"><a href="/p/a1">Widget</a> <span class="price">$9.99</span></li>
<li class="product sale" data-sku="B2"><a href="/p/b2">Gadget & Co</a> <span class="price">$19.50</span></li>
<li class="product" data-sku="C3"><a href="/p/c3">Gizmo</a></li>
</ul>
""";
var doc = new HtmlDocument();
doc.LoadHtml(html);
var items = doc.DocumentNode.SelectNodes("//li[contains(concat(' ', @class, ' '), ' product ')]");
foreach (var li in items ?? Enumerable.Empty<HtmlNode>())
{
string sku = li.GetAttributeValue("data-sku", "");
string name = HtmlEntity.DeEntitize(li.SelectSingleNode("a")!.InnerText);
string price = li.SelectSingleNode(".//span[@class='price']")?.InnerText ?? "n/a";
Console.WriteLine($"{sku} {name,-12} {price}");
}
var tables = doc.DocumentNode.SelectNodes("//table");
Console.WriteLine(tables is null ? "SelectNodes returned null" : $"{tables.Count} tables");
var sale = doc.DocumentNode.Descendants("li")
.Where(n => n.HasClass("sale"))
.Select(n => n.SelectSingleNode("a")!.GetAttributeValue("href", ""));
Console.WriteLine(string.Join(", ", sale));
A1 Widget $9.99
B2 Gadget & Co $19.50
C3 Gizmo n/a
SelectNodes returned null
/p/b2
Things to watch out for with HAP:
SelectNodesreturnsnull, not an empty collection, when nothing matches. This is the most common source ofNullReferenceExceptionin HAP code.InnerTextdoesn't decode entities. UseHtmlEntity.DeEntitize, otherwise you getGadget & Co.- Matching a class with XPath requires the
contains(concat(' ', @class, ' '), ' product ')idiom, because@class='product'doesn't matchclass="product sale".HasClasswith LINQ overDescendants()is often easier. - HAP's error recovery is its own, not the HTML5 algorithm, so the tree can differ from what a browser builds. For example it doesn't add the implicit
<html>,<body>or<tbody>elements, so//table/trmatches in HAP whiletable > trdoesn't match in AngleSharp. - Load a page from the web with
new HtmlWeb().Load(url)or, better, download it withHttpClientand callLoadHtml.
If you prefer CSS selectors with HAP, there are add-on packages, but at that point AngleSharp is the simpler choice.
| AngleSharp | HtmlAgilityPack | |
|---|---|---|
| Parsing | HTML5 standard, same tree as browsers | own lenient parser |
| Queries | CSS selectors, DOM API | XPath, LINQ |
| No match | null / empty collection |
null from SelectNodes |
| Entities in text | decoded | HtmlEntity.DeEntitize |
| URL resolution | Href, Source with a document address |
manual |
| Extras | CSS parsing, forms, HtmlSanitizer builds on it | XPath on HTML |
Summary
- Don't parse HTML with regular expressions or XML parsers. Use AngleSharp (or HtmlAgilityPack in existing code).
new HtmlParser().ParseDocument(html)never fails on broken markup and produces the same tree as a browser, including the implicit<html>,<body>and<tbody>.- Find elements with
QuerySelector/QuerySelectorAlland CSS selectors, readTextContentandGetAttribute. - Load documents through a
BrowsingContextwith an address (orOpenAsync(url)) soHrefandSourcereturn absolute URLs. - Remove
<script>and<style>before extracting text, and normalize whitespace. - Sanitize untrusted HTML with HtmlSanitizer. Encode untrusted text with
WebUtility.HtmlEncode. - Parsers don't run JavaScript. For client-rendered pages use the site's API or a headless browser.