HtmlAgilityPack for C# (.NET): Complete Guide with Examples
\n\n1. What It Is and Why It's Needed
\nHtmlAgilityPack is a powerful library for parsing HTML documents in the .NET ecosystem (C#, VB.NET, F#). It provides developers with a convenient API for navigating, searching, extracting, and modifying HTML code. Unlike standard XML parsers, HtmlAgilityPack is specifically designed to work with "dirty" HTML, which is often found on the real web: unclosed tags, incorrect attributes, nested errors, etc. The library automatically fixes such defects, creating a correct DOM tree.
\nWhy is it needed? Main use cases include: web scraping (extracting data from websites), automating web interface testing, migrating content between CMS systems, analyzing HTML reports, cleaning and normalizing HTML code, as well as creating custom HTML generators. Thanks to support for XPath and CSS selectors (via an extension), the library allows flexible and precise selection of the required elements.
\nHtmlAgilityPack is actively supported by the community, has open-source code, and is compatible with .NET Framework 4.5+, .NET Core 2.0+, .NET 5/6/7/8, as well as Xamarin and Unity. This makes it a universal tool for any .NET developer working with HTML.
\n2. Installation
\nThe library is installed via the NuGet Package Manager. Run one of the following commands in the Package Manager Console or in the .NET CLI terminal:
\n// Via .NET CLI\ndotnet add package HtmlAgilityPack\n\n// Via Package Manager Console\nInstall-Package HtmlAgilityPack\n\n// Or via NuGet UI: search for "HtmlAgilityPack" and install the latest stable version\n After installation, add the using directive at the beginning of the file:
\nusing HtmlAgilityPack;\n 3. Quick Start — Minimal Working Example
\nLet's look at a simple example: load an HTML string, find all links, and output their text and URL.
\nusing System;\nusing HtmlAgilityPack;\n\nclass Program\n{\n static void Main()\n {\n // 1. Create an HTML document\n var htmlDoc = new HtmlDocument();\n \n // 2. Load HTML (in reality, it could be from a file or the web)\n string html = @"\n \n \n \n
\n ";\n htmlDoc.LoadHtml(html);\n \n // 3. Select all <a> tags using XPath\n var links = htmlDoc.DocumentNode.SelectNodes("//a");\n \n // 4. Iterate over each and output the text and href\n if (links != null)\n {\n foreach (var link in links)\n {\n string text = link.InnerText.Trim();\n string href = link.GetAttributeValue("href", "");\n Console.WriteLine($"Text: {text}, URL: {href}");\n }\n }\n }\n}\n Execution result:
\nText: Example, URL: https://example.com\nText: PythonLib, URL: https://pythonlib.ru\n 4. Main Classes and Methods
\nBelow are the key classes and methods of HtmlAgilityPack with detailed descriptions and examples.
\n\n4.1. HtmlDocument — Main Class for Working with a Document
\nSignature: public class HtmlDocument
Description: Represents an entire HTML document. Allows