Edit HTML Document in C#

To edit an HTML document in C#, create or load an HTMLDocument, find elements with GetElementById() or QuerySelector(), update text and attributes, add or remove nodes, and save the changed document with HTMLDocument.Save(). Use InnerHTML when you need to replace markup inside an element.

Aspose.HTML for .NET represents HTML as a DOM tree based on the WHATWG DOM standard. If you already know HTML and JavaScript DOM concepts, the same document model will feel familiar: documents contain nodes, nodes can have children, and elements can have attributes, text, and markup content.

This article focuses on editing HTML structure and content: creating elements, setting attributes, appending nodes, removing nodes, and working with InnerHTML and OuterHTML. If you need to style HTML with inline, internal, or external CSS, see Edit CSS in HTML.

DOM Namespace and Core Types

A DOM tree is an in-memory representation of a document. The DOM is an API for accessing and manipulating document content. HTML documents consist of a tree with several kinds of nodes whose root is a Document. The DOM namespace includes the core types used to inspect and modify HTML documents.

Data typeUse it to work with
DocumentThe entire HTML, XML, or SVG document. It is the root of the document tree and provides primary access to document data.
EventTargetObjects that can receive dispatched DOM events.
NodeA single node in the document tree. It is the primary type for DOM tree operations.
ElementA DOM element based on Node; it represents HTML, XML, or SVG elements.
AttrAn attribute of an element.

The following DOM methods and properties are commonly used when editing HTML documents:

APIUse it to control
Document.GetElementById(elementId)Finds the first element with the specified ID, or returns null if no matching element exists.
Document.GetElementsByTagName(tagname)Returns elements with the specified tag name.
Document.CreateElement(localname)Creates an element of the specified type, or an HTMLUnknownElement if the tag name is not recognized.
Document.CreateTextNode(data)Creates a text node with the specified string.
Node.AppendChild(node)Adds a node to the end of the current node’s children.
Node.InsertBefore(node, child)Inserts a node before a reference child node.
Node.RemoveChild(child)Removes a child node from the current node.
Element.Remove()Removes the current element from the HTML DOM tree.
Element.SetAttribute(name, value)Sets or updates an element attribute.
Element.GetAttribute(name)Reads an element attribute value.
Element.InnerHTMLGets or sets markup contained inside an element.
Element.OuterHTMLGets the markup for the element itself and its content.

For the complete list of interfaces and methods represented in the DOM namespace, see the Aspose.HTML for .NET API Reference.

Create and Edit HTML Elements

You can edit HTML by inserting new nodes, removing nodes, or updating existing node content and attributes. If you need to create a new node, use methods such as CreateElement(), CreateTextNode(), CreateComment(), or CreateDocumentFragment() depending on the node type required by the workflow.

HTML elements can have attributes, text nodes, and children. The following example creates a paragraph, sets its id attribute, adds text, appends the paragraph to the document body, and saves the result.

When building a document tree, choose the node creation method that matches the content you need to add:

APIUse it to create
Document.CreateElement(localname)An HTML, XML, or SVG element with the specified tag name.
Document.CreateTextNode(data)A text node with the specified string value.
Document.CreateComment(data)An HTML comment node.
Document.CreateCDATASection(data)A CDATA section node.
Document.CreateDocumentFragment()A lightweight fragment for grouping nodes before insertion.
Document.CreateEntityReference(name)An entity reference node with the specified name.
Document.CreateProcessingInstruction(target, data)A processing instruction with the specified target and data.

To create and edit an HTML element in C#:

  1. Create an instance of the HTMLDocument class.
  2. Get the document body.
  3. Create a paragraph element with CreateElement("p").
  4. Set the paragraph id attribute with SetAttribute().
  5. Create a text node with CreateTextNode().
  6. Append the text node to the paragraph and the paragraph to the document body.
  7. Save the HTML document with Save().
 1// Edit HTML document using DOM Tree
 2
 3// Create an instance of an HTML document
 4using (HTMLDocument document = new HTMLDocument())
 5{
 6    HTMLElement body = document.Body;
 7
 8    // Create a paragraph element
 9    HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p");
10
11    // Set a custom attribute
12    p.SetAttribute("id", "my-paragraph");
13
14    // Create a text node
15    Text text = document.CreateTextNode("my first paragraph");
16
17    // Attach the text to the paragraph
18    p.AppendChild(text);
19
20    // Attach the paragraph to the document body
21    body.AppendChild(p);
22
23    // Save the HTML document to a file
24    document.Save(Path.Combine(OutputDir, "edit-document-tree.html"));
25}

The next C# example creates a more complex HTML document. It creates a <style> element, appends it to the document <head>, creates a paragraph with the gr class, adds text, saves the HTML file, and renders the result to PDF with PdfDevice.

To create a styled DOM tree and render it:

  1. Create an HTMLDocument instance.
  2. Create a <style> element and set its TextContent.
  3. Append the style element to the document <head>.
  4. Create a paragraph element and set its ClassName.
  5. Add text to the paragraph and append it to the document body.
  6. Save the HTML file and render the document to PDF when visual output is needed.
 1// Create and add new HTML elements using C#
 2
 3// Create an instance of an HTML document
 4using (HTMLDocument document = new HTMLDocument())
 5{
 6    // Create a <style> element and assign the green color for all elements with class-name equals 'gr'.
 7    Element style = document.CreateElement("style");
 8    style.TextContent = ".gr { color: green }";
 9
10    // Find the document <head> element and append the <style> element to it
11    Element head = document.GetElementsByTagName("head").First();
12    head.AppendChild(style);
13
14    // Create a paragraph element with class-name 'gr'.
15    HTMLParagraphElement p = (HTMLParagraphElement)document.CreateElement("p");
16    p.ClassName = "gr";
17
18    // Create a text node
19    Text text = document.CreateTextNode("Hello World!!");
20
21    // Append the text node to the paragraph
22    p.AppendChild(text);
23
24    // Append the paragraph to the document <body> element
25    document.Body.AppendChild(p);
26
27    // Save the HTML document to a file 
28    document.Save(Path.Combine(OutputDir, "using-dom.html"));
29
30    // Create an instance of the PDF output device and render the document into this device
31    using (PdfDevice device = new PdfDevice(Path.Combine(OutputDir, "using-dom.pdf")))
32    {
33        // Render HTML to PDF
34        document.RenderTo(device);
35    }
36}

Update an Existing HTML Document

A common editing task is to open an existing HTML file, find specific elements, update their text or attributes, and save the modified document. This workflow is useful when HTML is generated by another system and your application needs to adjust headings, links, metadata, or content blocks before publishing or conversion.

The following C# example creates a small source HTML file, loads it with HTMLDocument, updates the heading text, changes a link text and href attribute, and saves the result to a new HTML file.

To update an existing HTML document in C#:

  1. Prepare or load an existing HTML file.
  2. Create an HTMLDocument instance with the input file path.
  3. Find the target element with GetElementById() or QuerySelector().
  4. Update text with TextContent and attributes with SetAttribute().
  5. Save the edited document with Save().
 1using Aspose.Html;
 2using Aspose.Html.Dom;
 3using System.IO;
 4
 5string inputPath = "existing-document.html";
 6string outputPath = "updated-document.html";
 7
 8File.WriteAllText(inputPath,
 9    "<!DOCTYPE html>" +
10    "<html>" +
11    "<body>" +
12    "<h1 id='page-title'>Original Title</h1>" +
13    "<p>Download the source file from the old link.</p>" +
14    "<a class='download-link' href='old-file.html'>Old download link</a>" +
15    "</body>" +
16    "</html>");
17
18using (HTMLDocument document = new HTMLDocument(inputPath))
19{
20    Element heading = document.GetElementById("page-title");
21    if (heading != null)
22    {
23        heading.TextContent = "Updated HTML Document";
24    }
25
26    Element downloadLink = document.QuerySelector("a.download-link");
27    if (downloadLink != null)
28    {
29        downloadLink.TextContent = "Download updated file";
30        downloadLink.SetAttribute("href", "updated-file.html");
31        downloadLink.SetAttribute("title", "Download the updated HTML file");
32    }
33
34    document.Save(outputPath);
35}

The figure below compares the HTML document before and after editing: (a) the source document with the original heading and old download link; (b) the updated document after changing the heading text, link text, href, and title attribute.

HTML document before and after updating text and link attributes in C#

Remove or Replace an Element

Use Remove() when an element must disappear from the DOM tree. Use InnerHTML when the element itself should remain, but its child markup must be replaced. These two operations solve different editing tasks: removing an obsolete banner, script, or notice is not the same as replacing the content of an existing container.

The following C# example removes a notification block from the document and replaces the content inside the main content section. The section element remains in the document, but its child markup is rewritten.

To remove or replace HTML content in C#:

  1. Load the HTML document you want to edit.
  2. Find the removable element with GetElementById().
  3. Call Remove() to delete that element from the DOM tree.
  4. Find the container whose content should be replaced.
  5. Assign new markup to InnerHTML.
  6. Save the changed HTML document.
 1using Aspose.Html;
 2using Aspose.Html.Dom;
 3using System.IO;
 4
 5string inputPath = "page-with-old-content.html";
 6string outputPath = "page-with-updated-content.html";
 7
 8File.WriteAllText(inputPath,
 9    "<!DOCTYPE html>" +
10    "<html>" +
11    "<body>" +
12    "<div id='notification'>This temporary notice should be removed.</div>" +
13    "<section id='content'><p>Old content block.</p></section>" +
14    "</body>" +
15    "</html>");
16
17using (HTMLDocument document = new HTMLDocument(inputPath))
18{
19    Element notification = document.GetElementById("notification");
20    if (notification != null)
21    {
22        notification.Remove();
23    }
24
25    Element content = document.GetElementById("content");
26    if (content != null)
27    {
28        content.InnerHTML = "<h2>Updated Content</h2><p>This section was replaced with new HTML markup.</p>";
29    }
30
31    document.Save(outputPath);
32}

The figure below shows the result of removing and replacing HTML content: (a) the source document with a temporary notification and old content block; (b) the updated document after removing the notification and replacing the section content with new HTML markup.

HTML document before and after removing an element and replacing content in C#

Edit HTML with InnerHTML and OuterHTML

DOM methods are useful when you need structured editing. However, sometimes it is simpler to work with markup as a string. Use InnerHTML to replace the content inside an element, and OuterHTML to inspect the element markup together with its children.

The following example creates an empty document, prints the initial document markup, assigns new markup to document.Body.InnerHTML, and prints the updated document markup from document.DocumentElement.OuterHTML.

To edit HTML body content as markup:

  1. Create an HTMLDocument instance.
  2. Read document.DocumentElement.OuterHTML to inspect the initial markup.
  3. Assign HTML markup to document.Body.InnerHTML.
  4. Read document.DocumentElement.OuterHTML again to get the updated HTML string.
 1// Edit HTML body content and get modified document as string
 2
 3// Create an instance of an HTML document
 4using (HTMLDocument document = new HTMLDocument())
 5{
 6    // Write the content of the HTML document into the console output
 7    Console.WriteLine(document.DocumentElement.OuterHTML); // output: <html><head></head><body></body></html>
 8
 9    // Set the content of the body element
10    document.Body.InnerHTML = "<p>HTML is the standard markup language for Web pages.</p>";
11
12    // Set an html variable for the document content viewing
13    string html = document.DocumentElement.OuterHTML;
14
15    // Write the content of the HTML document into the console output
16    Console.WriteLine(html); // output: <html><head></head><body><p>HTML is the standard markup language for Web pages.</p></body></html>
17}

Common HTML Editing Issues

ProblemCauseSolution
Created element is not visible in outputThe element was created but not appended to the document tree.Append the element to document.Body or another parent node before saving.
Attribute changes are missingThe wrong element was selected or SetAttribute() was not called on the target element.Select the target element first, then call SetAttribute(name, value) on that element.
InnerHTML replaces existing contentAssigning InnerHTML replaces all current child markup inside the element.Use DOM methods such as AppendChild() when you need to preserve existing children.
Output file is not updatedThe document was modified in memory but not saved.Call HTMLDocument.Save() after DOM changes are complete.
Removed element still appearsThe wrong node was selected, or the document was saved before Remove() was called.Check the selector or ID, call Remove() on the target element, and save the document after the change.
Styling logic makes the DOM article too broadCSS editing has its own workflow and examples.Use Edit CSS in HTML for inline, internal, and external CSS examples.

FAQ

How do I edit an HTML document in C#?

Create or load an HTMLDocument, use DOM methods to create or update nodes, set attributes, append elements to the tree, and save the changed document.

How do I update an existing HTML file?

Load the file with HTMLDocument, find the target element, update TextContent, InnerHTML, or attributes, and save the document to the same or a new path.

How do I add a new element to HTML?

Use Document.CreateElement() to create the element, set attributes or text if needed, and call AppendChild() to attach it to the target parent node.

How do I remove an HTML element?

Find the target element with GetElementById() or QuerySelector(), call Remove(), and save the updated document.

What is the difference between InnerHTML and OuterHTML?

InnerHTML represents markup inside an element. OuterHTML represents the element itself together with its child markup.

Can I edit CSS in the same DOM workflow?

Yes. CSS can be edited through attributes, <style> elements, or linked CSS files. For dedicated examples, see Edit CSS in HTML.

Other Platforms

Related Articles

The complete C# examples and data files are available in the Aspose.HTML for .NET GitHub repository.