Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Aspose.HTML for .NET lets you create HTML documents from scratch, load existing HTML from a file or URL, build a document from an in-memory string or stream, and work with the DOM before saving or converting the result. The central API is the HTMLDocument class, which represents the HTML document tree in memory.
Use HTMLDocument constructors to create or load HTML in C#. You can start with an empty document, open an HTML file or URL, pass HTML markup as a string or stream, edit the DOM, and then save or convert the document.
The HTMLDocument implementation is based on the W3C DOM and WHATWG DOM specifications, so the object model follows familiar browser concepts: document, elements, text nodes, attributes, and child nodes. After loading a document, you can read HTML, add or remove nodes, update attributes, change text, apply styles, or pass the document to a conversion workflow.
Use this article when you need to choose the correct constructor or loading pattern for a C# application.
| Source or task | Recommended API |
|---|---|
| Create an empty HTML document | new HTMLDocument() |
| Build HTML with DOM methods | HTMLDocument, CreateTextNode(), AppendChild() |
| Load an HTML file | new HTMLDocument(filePath) |
| Load HTML from a URL | new HTMLDocument(url) |
| Create HTML from a string | new HTMLDocument(html, baseUrl) |
| Create HTML from a stream | new HTMLDocument(stream, baseUrl) |
| Create an SVG document from markup | new SVGDocument(svg, baseUrl) |
| Load a document without blocking the main thread | HTMLDocument.Navigate() with OnReadyStateChange or OnLoad events |
The HTMLDocument class is the starting point for most Aspose.HTML for .NET workflows. You can create a new document, load existing HTML, inspect the DOM, modify document nodes, and save the result as HTML or convert it to another format.
Use the default HTMLDocument() constructor when you need an empty document that can be filled later.
HTMLDocument instance with the default constructor.The following example creates an empty HTML document and saves it to a file:
1// Create an empty HTML document using C#
2
3// Prepare an output path for a document saving
4string documentPath = Path.Combine(OutputDir, "create-empty-document.html");
5
6// Initialize an empty HTML Document
7using (HTMLDocument document = new HTMLDocument())
8{
9 // Work with the document
10
11 // Save the document to a file
12 document.Save(documentPath);
13}After saving, the output file contains the initial HTML structure, including <html>, <head>, and <body> elements. For more saving options, see
Save HTML Document in C#.
Use DOM methods when the HTML structure should be generated programmatically.
HTMLDocument.The following example creates a text node, appends it to the document body, and saves the new HTML file:
1// Create an HTML document using C#
2
3// Prepare an output path for a document saving
4string documentPath = Path.Combine(OutputDir, "create-new-document.html");
5
6// Initialize an empty HTML Document
7using (HTMLDocument document = new HTMLDocument())
8{
9 // Create a text node and add it to the document
10 Text text = document.CreateTextNode("Hello, World!");
11 document.Body.AppendChild(text);
12
13 // Save the document to a disk
14 document.Save(documentPath);
15}For more DOM editing patterns, see Edit HTML Document in C#.
Use the HTMLDocument(string) constructor when the source HTML already exists on disk.
HTMLDocument instance from that file path.The following example loads an HTML file and prints the root element markup:
1// Load HTML from a file using C#
2
3string htmlFile = Path.Combine(OutputDir, "load-from-file.html");
4
5// Prepare a load-from-file.html document
6File.WriteAllText(htmlFile, "Hello, World!");
7
8// Load from the load-from-file.html
9using (HTMLDocument document = new HTMLDocument(htmlFile))
10{
11 // Write the document content to the output stream
12 Console.WriteLine(document.DocumentElement.OuterHTML);
13}If you need to load an existing HTML file, work with it, and save a new copy, use the same constructor and call Save() after changes are applied.
1// Load an HTML documment from a file using C#
2
3// Prepare a file path
4string documentPath = Path.Combine(DataDir, "sprite.html");
5
6// Initialize an HTML document from the file
7using (HTMLDocument document = new HTMLDocument(documentPath))
8{
9 // Work with the document
10
11 // Save the document to a disk
12 document.Save(Path.Combine(OutputDir, "sprite_out.html"));
13}Use URL loading when your application needs to open a remote HTML page directly.
HTMLDocument constructor.The following example loads an HTML document from a URL and writes the resulting markup to the console:
If the URL cannot be reached, Aspose.HTML throws a
DOMException with the NetworkError code.
1// Load HTML from a URL using C#
2
3// Load a document from 'https://docs.aspose.com/html/files/document.html' web page
4using (HTMLDocument document = new HTMLDocument("https://docs.aspose.com/html/files/document.html"))
5{
6 string html = document.DocumentElement.OuterHTML;
7
8 // Write the document content to the output stream
9 Console.WriteLine(html);
10}When HTML markup is already available in memory as a System.String or System.IO.Stream, you do not need to create a temporary source file. Pass the markup or stream to a specialized HTMLDocument constructor together with a base URL.
Pass a valid baseUrl when HTML markup contains relative links to images, stylesheets, scripts, fonts, or other resources. Aspose.HTML uses the base URL to resolve those resources during document loading.
Use the HTMLDocument(string, string) constructor when HTML markup is stored in a C# string.
HTMLDocument constructor.The following example creates an HTML document from a string and saves it as an HTML file:
1// Create HTML from a string using C#
2
3// Prepare HTML code
4string html_code = "<p>Hello, World!</p>";
5
6// Initialize a document from the string variable
7using (HTMLDocument document = new HTMLDocument(html_code, "."))
8{
9 // Save the document to a disk
10 document.Save(Path.Combine(OutputDir, "create-from-string.html"));
11}Use the HTMLDocument(stream, string) constructor when markup comes from memory, a response body, storage, or another stream-based source.
HTMLDocument constructor.The following example creates a document from a memory stream:
1// Load HTML from a stream using C#
2
3// Create a memory stream object
4using (MemoryStream mem = new MemoryStream())
5using (StreamWriter sw = new StreamWriter(mem))
6{
7 // Write the HTML code into memory object
8 sw.Write("<p>Hello, World! I love HTML!</p>");
9
10 // It is important to set the position to the beginning, since HTMLDocument starts the reading exactly from the current position within the stream
11 sw.Flush();
12 mem.Seek(0, SeekOrigin.Begin);
13
14 // Initialize a document from the string variable
15 using (HTMLDocument document = new HTMLDocument(mem, "."))
16 {
17 // Save the document to disk
18 document.Save(Path.Combine(OutputDir, "load-from-stream.html"));
19 }
20}Aspose.HTML for .NET also works with SVG documents through SVGDocument. SVG and HTML documents share the same DOM foundation, so many loading, reading, editing, and saving concepts are similar.
Use SVGDocument(string, string) when SVG markup is already available in memory.
SVGDocument.The following example creates an SVG document that contains a circle and writes its markup to the console:
1// Load SVG from a string using C#
2
3// Initialize an SVG document from a string object
4using (SVGDocument document = new SVGDocument("<svg xmlns='http://www.w3.org/2000/svg'><circle cx='50' cy='50' r='40'/></svg>", "."))
5{
6 // Write the document content to the output stream
7 Console.WriteLine(document.DocumentElement.OuterHTML);
8}For more SVG-specific workflows, see How to Work with Aspose.SVG API.
MHTML is a web archive format that can contain HTML and related resources such as CSS, JavaScript, images, and audio files. EPUB is an electronic publication format used by many eReaders and reading applications.
Aspose.HTML for .NET supports MHTML and EPUB primarily for rendering and conversion workflows. These formats are not handled like editable HTMLDocument sources in this article. To convert MHTML or EPUB to PDF, XPS, images, and other supported output formats, see
Converting Between Formats in C#.
Loading a document can take time because the library may need to load the HTML source, linked resources, and scripts. For responsive applications, you can start loading with Navigate() and handle completion through document events.
Use OnReadyStateChange when you need to check when the document reaches the complete state.
HTMLDocument.OnReadyStateChange.Navigate() with the target URL.complete.The following example loads a remote document asynchronously and waits for the completed state:
1// Load HTML asynchronously using C#
2
3// Initialize an AutoResetEvent
4AutoResetEvent resetEvent = new AutoResetEvent(false);
5
6// Create an instance of an HTML document
7HTMLDocument document = new HTMLDocument();
8
9// Create a string variable for the OuterHTML property reading
10string outerHTML = string.Empty;
11
12// Subscribe to ReadyStateChange event
13// This event will be fired during the document loading process
14document.OnReadyStateChange += (sender, @event) =>
15{
16 // Check the value of the ReadyState property
17 // This property is representing the status of the document. For detail information please visit https://www.w3schools.com/jsref/prop_doc_readystate.asp
18 if (document.ReadyState == "complete")
19 {
20 // Fill the outerHTML variable by value of loaded document
21 outerHTML = document.DocumentElement.OuterHTML;
22 resetEvent.Set();
23 }
24};
25
26// Navigate asynchronously at the specified Uri
27document.Navigate("https://docs.aspose.com/html/files/document.html");
28
29// Here the outerHTML is empty yet
30
31Console.WriteLine($"outerHTML = {outerHTML}");
32
33// Wait 5 seconds for the file to load
34
35// Here the outerHTML is filled
36Console.WriteLine("outerHTML = {0}", outerHTML);The OnLoad event is another way to react when asynchronous document loading is complete.
HTMLDocument.OnLoad.Navigate() with the target URL.The following example uses the OnLoad event for asynchronous document loading:
1// Handle an HTML document load using C#
2
3// Initialize an AutoResetEvent
4AutoResetEvent resetEvent = new AutoResetEvent(false);
5
6// Initialize an HTML document
7HTMLDocument document = new HTMLDocument();
8bool isLoading = false;
9
10// Subscribe to the OnLoad event
11// This event will be fired once the document is fully loaded
12document.OnLoad += (sender, @event) =>
13{
14 isLoading = true;
15 resetEvent.Set();
16};
17
18// Navigate asynchronously at the specified Uri
19document.Navigate("https://docs.aspose.com/html/files/document.html");
20
21Console.WriteLine("outerHTML = {0}", document.DocumentElement.OuterHTML);| Issue | Cause | Fix |
|---|---|---|
| Relative images, styles, or fonts are not loaded | The document was created from a string or stream without a valid base URL. | Pass a base URL that points to the folder or address where relative resources should be resolved. |
| A stream-based document is empty | The stream position remained at the end after writing markup. | Reset the stream position before passing it to the HTMLDocument constructor. |
URL loading fails with NetworkError | The remote resource is unavailable or the URL cannot be reached. | Check the URL, network access, redirects, and environment configuration before loading the document. |
| Saved HTML contains only the initial structure | An empty HTMLDocument was saved before content was added. | Add DOM nodes or load source HTML before calling Save(). |
| Asynchronous code reads incomplete markup | The document is inspected before loading finishes. | Wait for OnReadyStateChange with complete or handle the OnLoad event before reading the DOM. |
| MHTML or EPUB cannot be edited like HTML | These formats are supported for rendering workflows, not as general editable HTMLDocument sources. | Use conversion APIs for MHTML and EPUB, or convert the content to an editable HTML workflow first. |
Create an HTMLDocument with the default constructor, add DOM nodes if needed, and save it with Save().
Pass the file path to an HTMLDocument constructor. After loading, you can read the DOM, update content, save the document, or convert it.
Use the HTMLDocument(string, string) constructor. The first argument is HTML markup, and the second argument is the base URL for resolving relative resources.
The base URL is used to resolve relative resource paths in HTML strings and streams. Without it, linked images, CSS, scripts, or fonts may not load correctly.
Yes. Pass the URL to an HTMLDocument constructor. If the URL is unavailable, the library reports a network loading error.
Yes. Use SVGDocument for SVG content. SVG documents use a DOM model similar to HTML documents and can be read, edited, saved, or converted.
No. MHTML and EPUB are supported for rendering and conversion scenarios. Use the converter APIs when you need to render those formats to PDF, XPS, images, or other outputs.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.