Create or Load HTML Documents in C#

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 taskRecommended API
Create an empty HTML documentnew HTMLDocument()
Build HTML with DOM methodsHTMLDocument, CreateTextNode(), AppendChild()
Load an HTML filenew HTMLDocument(filePath)
Load HTML from a URLnew HTMLDocument(url)
Create HTML from a stringnew HTMLDocument(html, baseUrl)
Create HTML from a streamnew HTMLDocument(stream, baseUrl)
Create an SVG document from markupnew SVGDocument(svg, baseUrl)
Load a document without blocking the main threadHTMLDocument.Navigate() with OnReadyStateChange or OnLoad events

Create and Load HTML Documents

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.

Create an Empty HTML Document

Use the default HTMLDocument() constructor when you need an empty document that can be filled later.

  1. Create an HTMLDocument instance with the default constructor.
  2. Add nodes, attributes, or styles if the document should contain custom content.
  3. Save the document to an output path.

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#.

Create a New HTML Document with DOM Nodes

Use DOM methods when the HTML structure should be generated programmatically.

  1. Create an empty HTMLDocument.
  2. Create a text node with CreateTextNode().
  3. Add the node to the document body with AppendChild().
  4. Save the generated HTML document.

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#.

Load HTML from a File

Use the HTMLDocument(string) constructor when the source HTML already exists on disk.

  1. Prepare the path to the source HTML file.
  2. Create an HTMLDocument instance from that file path.
  3. Read, modify, save, or convert the loaded document.

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}

Load HTML from a URL

Use URL loading when your application needs to open a remote HTML page directly.

  1. Pass the page URL to an HTMLDocument constructor.
  2. Let Aspose.HTML load the HTML and related resources available to the document.
  3. Read the DOM, extract markup, edit nodes, or convert the loaded page.

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}

Create Documents from HTML Code

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.

Create HTML from a String

Use the HTMLDocument(string, string) constructor when HTML markup is stored in a C# string.

  1. Prepare an HTML string.
  2. Pass the string and base URL to the HTMLDocument constructor.
  3. Save or process the created document.

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}

Create HTML from a Stream

Use the HTMLDocument(stream, string) constructor when markup comes from memory, a response body, storage, or another stream-based source.

  1. Write or receive HTML markup into a stream.
  2. Reset the stream position before loading if the stream was just written.
  3. Pass the stream and base URL to the HTMLDocument constructor.
  4. Save, edit, or convert the created document.

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}

Create SVG, MHTML, and EPUB Documents

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.

Create an SVG Document from a String

Use SVGDocument(string, string) when SVG markup is already available in memory.

  1. Prepare SVG markup as a string.
  2. Pass the SVG string and base URL to SVGDocument.
  3. Read, edit, save, or convert the SVG document.

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 and EPUB Support

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#.

Load HTML Asynchronously

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

Use OnReadyStateChange when you need to check when the document reaches the complete state.

  1. Create an empty HTMLDocument.
  2. Subscribe to OnReadyStateChange.
  3. Call Navigate() with the target URL.
  4. Read or process the document after the ready state becomes 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);

Use the Load Event

The OnLoad event is another way to react when asynchronous document loading is complete.

  1. Create an empty HTMLDocument.
  2. Subscribe to OnLoad.
  3. Call Navigate() with the target URL.
  4. Continue processing after the load event is raised.

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);

Common Document Creation Issues

IssueCauseFix
Relative images, styles, or fonts are not loadedThe 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 emptyThe stream position remained at the end after writing markup.Reset the stream position before passing it to the HTMLDocument constructor.
URL loading fails with NetworkErrorThe 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 structureAn empty HTMLDocument was saved before content was added.Add DOM nodes or load source HTML before calling Save().
Asynchronous code reads incomplete markupThe 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 HTMLThese 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.

FAQ

How do I create an empty HTML document in C#?

Create an HTMLDocument with the default constructor, add DOM nodes if needed, and save it with Save().

How do I load an HTML file in C#?

Pass the file path to an HTMLDocument constructor. After loading, you can read the DOM, update content, save the document, or convert it.

How do I create an HTML document from a string?

Use the HTMLDocument(string, string) constructor. The first argument is HTML markup, and the second argument is the base URL for resolving relative resources.

Why does the base URL matter?

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.

Can I load HTML from a remote URL?

Yes. Pass the URL to an HTMLDocument constructor. If the URL is unavailable, the library reports a network loading error.

Can I create SVG documents with Aspose.HTML for .NET?

Yes. Use SVGDocument for SVG content. SVG documents use a DOM model similar to HTML documents and can be read, edited, saved, or converted.

Can I create editable MHTML or EPUB documents in the same way?

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.

Other Platforms

Related Articles