Edit HTML Document – Edit HTML File – C#
As we already mentioned in the article Create HTML Document the implementation of the HTMLDocument as well as the whole DOM are based on WHATWG DOM standard. So, it is easy to use Aspose.HTML for .NET having a basic knowledge of HTML and JavaScript languages.
DOM namespace
A DOM tree is an in-memory representation of a document. The DOM is an API for accessing and manipulating documents content. HTML documents consist of a tree that contains several kinds of nodes whose root is a Document. The DOM namespace is represented with the following fundamental data types:
Data type | Description |
---|---|
Document | The Document class represents the entire HTML, XML or SVG document. Conceptually, it is the root of the document tree and provides the primary access to the document’s data. |
EventTarget | The EventTarget class is implemented by all Nodes in an implementation that supports the DOM Event Model. An EventTarget object represents a target to which an event can be dispatched when something has occurred. |
Node | The Node class is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. |
Element | The element type is based on node and represents a base class for HTML, XML or SVG DOM. |
Attr | The Attr class represents an attribute in an Element object. Typically the allowable values for the attribute are defined in a schema associated with the document. |
The following is a brief list of useful API methods provides by the core data types:
Method | Description |
---|---|
Document.GetElementById(elementId ) | The method, when invoked, must return the first element whose ID is elementId and null if there is no such element otherwise. |
Document.GetElementsByTagName(tagname ) | The method must return the list of elements with the given name. |
Document.CreateElement(localname ) | The method creates an element of the type specified, or an HTMLUnknownElement if tagname isn’t recognized. |
Node.AppendChild(node ) | The method adds a node to the end of the list of children of a specified parent node. |
Element.SetAttribute(name, value ) | Sets the value of an attribute on the specified element. |
Element.GetAttribute(name ) | The method returns the value of a specified attribute on the element. |
Element.innerHTML | The property returns a fragment of markup contained within the element. |
For a complete list of interfaces and methods represented in the DOM namespace please visit API Reference Source.
Edit HTML
There are many ways you can edit HTML by using our library. You can modify the document by inserting new nodes, removing, or editing the content of existing nodes. If you need to create a new node, the following methods are ones that need to be invoked:
Method | Description |
---|---|
Document.CreateCDATASection(data ) | Creates a CDATASection node whose value is the specified string. |
Document.CreateComment(data ) | Creates a Comment node given the specified string. |
Document.CreateDocumentFragment() | Creates an empty DocumentFragment object. |
Document.CreateElement(localname ) | Creates an element of the type specified. |
Document.CreateEntityReference(name ) | Creates an EntityReference object. |
Document.CreateProcessingInstruction(target, data ) | Creates an ProcessingInstruction with the specified name and data. |
Document.CreateTextNode(data ) | Creates a Text node given the specified string. |
Once you have new nodes are created, there are several methods in the DOM that can help you to insert nodes into the document tree. The following list describes the most common way of inserting nodes:
Method | Description |
---|---|
Node.InsertBefore(node, child ) | Inserts the node before the reference child node. |
Node.AppendChild(node ) | Adds the node to the list of children of the current node. |
Node.RemoveChild(child ) | Removes the child node from the list of children. |
Element.Remove() | Removes this instance from the HTML DOM tree. |
You can download the complete examples and data files from GitHub.
Edit a Document Tree
HTML documents consist of a tree of elements. Each element is denoted in the source by a start tag, such as <body>
, and an end tag, such as </body>
. Elements can have attributes, which control how the elements work. Aspose.HTML for .NET API supports a set of HTML elements that are defined in HTML Standard, along with rules about how the elements can be nested.
Consider simple steps to create and edit HTML. The document will contain a text paragraph with an id
attribute:
- Create an instance of an HTML document.
- Create a paragraph element
<p>
. - Set the
id
attribute for the paragraph element. - Create a text node.
- Add the text to the paragraph.
- Add the paragraph to the document body.
- Save the HTML document to a file.
1// Create an instance of an HTML document
2using (var document = new HTMLDocument())
3{
4 var body = document.Body;
5
6 // Create a paragraph element
7 var p = (HTMLParagraphElement)document.CreateElement("p");
8
9 // Set a custom attribute
10 p.SetAttribute("id", "my-paragraph");
11
12 // Create a text node
13 var text = document.CreateTextNode("my first paragraph");
14
15 // Attach the text to the paragraph
16 p.AppendChild(text);
17
18 // Attach the paragraph to the document body
19 body.AppendChild(p);
20
21 // Save the HTML document to a file
22 document.Save(Path.Combine(OutputDir, "edit-document-tree.html"));
23}
Let’s take a look at creating a more complex HTML document. Each HTML document is represented as a node tree, and some of the nodes in a tree can have children. The following code snippet shows how to edit HTML document using DOM Tree and the mentioned above functional:
1// Create an instance of an HTML document
2using (var document = new HTMLDocument())
3{
4 // Create a <style> element and assign the green color for all elements with class-name equals 'gr'.
5 var style = document.CreateElement("style");
6 style.TextContent = ".gr { color: green }";
7
8 // Find the document <head> element and append the <style> element to it
9 var head = document.GetElementsByTagName("head").First();
10 head.AppendChild(style);
11
12 // Create a paragraph element with class-name 'gr'.
13 var p = (HTMLParagraphElement)document.CreateElement("p");
14 p.ClassName = "gr";
15
16 // Create a text node
17 var text = document.CreateTextNode("Hello World!!");
18
19 // Append the text node to the paragraph
20 p.AppendChild(text);
21
22 // Append the paragraph to the document <body> element
23 document.Body.AppendChild(p);
24
25 // Save the HTML document to a file
26 document.Save(Path.Combine(OutputDir, "using-dom.html"));
27
28 // Create an instance of the PDF output device and render the document into this device
29 using (var device = new PdfDevice(Path.Combine(OutputDir, "using-dom.pdf")))
30 {
31 // Render HTML to PDF
32 document.RenderTo(device);
33 }
34}
Using InnerHTML & OuterHTML properties
Having DOM objects gives you a powerful tool to manipulate with an HTML Document. However, sometime much better to work just with System.String. The following code snippet shows you how to use the InnerHTML & OuterHTML properties to edit HTML.
1// Create an instance of an HTML document
2using (var document = new HTMLDocument())
3{
4 // Write the content of the HTML document into the console output
5 Console.WriteLine(document.DocumentElement.OuterHTML); // output: <html><head></head><body></body></html>
6
7 // Set the content of the body element
8 document.Body.InnerHTML = "<p>HTML is the standard markup language for Web pages.</p>";
9
10 // Set an html variable for the document content viewing
11 var html = document.DocumentElement.OuterHTML;
12
13 // Write the content of the HTML document into the console output
14 Console.WriteLine(html); // output: <html><head></head><body><p>HTML is the standard markup language for Web pages.</p></body></html>
15}
Edit CSS
Cascading Style Sheets (CSS) is a style sheet language used for describing how web pages look in the browser. CSS can be added to HTML documents as an inline, internal, and external way. Thus you can set the unique style to a single HTML element using inline CSS, or for multiple web pages to share formatting by specifying the relevant CSS in a separate .css file. Aspose.HTML not only supports CSS out-of-the-box but also gives you instrumentsto manage document styles on the fly before converting the HTML document to other formats, as shown below.
Inline CSS
When CSS is written using the style
attribute inside of an HTML tag, it’s called an “inline style CSS”. The Inline CSS gives you to apply an individual style to one HTML element at a time. You set CSS to an HTML element by using the style
attribute with any CSS properties defined within it.
In the following code snippet, you can see how to specify CSS style properties for an HTML <p>
element.
1// Create an instance of an HTML document with specified content
2var content = "<p>InlineCSS </p>";
3using (var document = new HTMLDocument(content, "."))
4{
5 // Find the paragraph element to set a style
6 var paragraph = (HTMLElement)document.GetElementsByTagName("p").First();
7
8 // Set the style attribute
9 paragraph.SetAttribute("style", "font-size:250%; font-family:verdana; color:#cd66aa");
10
11 // Save the HTML document to a file
12 document.Save(Path.Combine(OutputDir, "edit-inline-css.html"));
13
14 // Create an instance of PDF output device and render the document into this device
15 using (var device = new PdfDevice(Path.Combine(OutputDir, "edit-inline-css.pdf")))
16 {
17 // Render HTML to PDF
18 document.RenderTo(device);
19 }
20}
In this particular example, color, font-size and font-family apply to the <p>
element. The fragment of rendered pdf page looks like this:
Internal CSS
The internal CSS styling option is popular for applying properties to individual pages by encasing all styles in the <style>
element placed it in the <head>
of HTML documents.
1// Create an instance of an HTML document with specified content
2var content = "<div><p>Internal CSS</p><p>An internal CSS is used to define a style for a single HTML page</p></div>";
3using (var document = new HTMLDocument(content, "."))
4{
5 var style = document.CreateElement("style");
6 style.TextContent = ".frame1 { margin-top:50px; margin-left:50px; padding:20px; width:360px; height:90px; background-color:#a52a2a; font-family:verdana; color:#FFF5EE;} \r\n" +
7 ".frame2 { margin-top:-90px; margin-left:160px; text-align:center; padding:20px; width:360px; height:100px; background-color:#ADD8E6;}";
8
9 // Find the document header element and append the style element to the header
10 var head = document.GetElementsByTagName("head").First();
11 head.AppendChild(style);
12
13 // Find the first paragraph element to inspect the styles
14 var paragraph = (HTMLElement)document.GetElementsByTagName("p").First();
15 paragraph.ClassName = "frame1";
16
17 // Find the last paragraph element to inspect the styles
18 var lastParagraph = (HTMLElement)document.GetElementsByTagName("p").Last();
19 lastParagraph.ClassName = "frame2";
20
21 // Set a color to the first paragraph
22 paragraph.Style.FontSize = "250%";
23 paragraph.Style.TextAlign = "center";
24
25 // Set a font-size to the last paragraph
26 lastParagraph.Style.Color = "#434343";
27 lastParagraph.Style.FontSize= "150%";
28 lastParagraph.Style.FontFamily = "verdana";
29
30 // Save the HTML document to a file
31 document.Save(Path.Combine(OutputDir, "edit-internal-css.html"));
32
33 // Create the instance of the PDF output device and render the document into this device
34 using (var device = new PdfDevice(Path.Combine(OutputDir, "edit-internal-css.pdf")))
35 {
36 // Render HTML to PDF
37 document.RenderTo(device);
38 }
39}
In this example, we use internal CSS and also declare additional style properties for individual elements using the Style property of the HTMLElement class. The figure illustrates the fragment of rendered “edit-internal-css.pdf” file:
External CSS
An external style sheet can be written in any text editor, and saved with a .css extension. It is a standalone CSS file that is linked from a web page. The advantage of external CSS is that it can be created once and the rules applied to multiple web pages.
Example 1
Let’s look at an example of an external CSS realization in which we use a link to a URL-address of a CSS file:
1// Create an instance of HTML document with specified content
2var htmlContent = "<link rel=\"stylesheet\" href=\"https://docs.aspose.com/html/net/edit-html-document/external.css\" type=\"text/css\" />\r\n" +
3 "<div class=\"rect1\" ></div>\r\n" +
4 "<div class=\"rect2\" ></div>\r\n" +
5 "<div class=\"frame\">\r\n" +
6 "<p style=\"font-size:2.5em; color:#ae4566;\"> External CSS </p>\r\n" +
7 "<p class=\"rect3\"> An external CSS can be created once and applied to multiple web pages</p></div>\r\n";
8
9using (var document = new HTMLDocument(htmlContent, "."))
10{
11 // Save the HTML document to a file
12 document.Save(Path.Combine(OutputDir, "external-css.html"));
13
14 // Create the instance of the PDF output device and render the document into this device
15 using (var device = new PdfDevice(Path.Combine(OutputDir, "external-css.pdf")))
16 {
17 // Render HTML to PDF
18 document.RenderTo(device);
19 }
20}
The result of the external CSS applying looks like this:
Example 2
You can write content for a CSS file in a string and save it to a separate linked file how it is shown in the following example:
1// Prepare content of a CSS file
2var styleContent = ".flower1 { width:120px; height:40px; border-radius:20px; background:#4387be; margin-top:50px; } \r\n" +
3 ".flower2 { margin-left:0px; margin-top:-40px; background:#4387be; border-radius:20px; width:120px; height:40px; transform:rotate(60deg); } \r\n" +
4 ".flower3 { transform:rotate(-60deg); margin-left:0px; margin-top:-40px; width:120px; height:40px; border-radius:20px; background:#4387be; }\r\n" +
5 ".frame { margin-top:-50px; margin-left:310px; width:160px; height:50px; font-size:2em; font-family:Verdana; color:grey; }\r\n";
6
7// Prepare a linked CSS file
8File.WriteAllText("flower.css", styleContent);
9
10// Create an instance of an HTML document with specified content
11var htmlContent = "<link rel=\"stylesheet\" href=\"flower.css\" type=\"text/css\" /> \r\n" +
12 "<div style=\"margin-top: 80px; margin-left:250px; transform: scale(1.3);\" >\r\n" +
13 "<div class=\"flower1\" ></div>\r\n" +
14 "<div class=\"flower2\" ></div>\r\n" +
15 "<div class=\"flower3\" ></div></div>\r\n" +
16 "<div style = \"margin-top: -90px; margin-left:120px; transform:scale(1);\" >\r\n" +
17 "<div class=\"flower1\" style=\"background: #93cdea;\"></div>\r\n" +
18 "<div class=\"flower2\" style=\"background: #93cdea;\"></div>\r\n" +
19 "<div class=\"flower3\" style=\"background: #93cdea;\"></div></div>\r\n" +
20 "<div style =\"margin-top: -90px; margin-left:-80px; transform: scale(0.7);\" >\r\n" +
21 "<div class=\"flower1\" style=\"background: #d5effc;\"></div>\r\n" +
22 "<div class=\"flower2\" style=\"background: #d5effc;\"></div>\r\n" +
23 "<div class=\"flower3\" style=\"background: #d5effc;\"></div></div>\r\n" +
24 "<p class=\"frame\">External</p>\r\n" +
25 "<p class=\"frame\" style=\"letter-spacing:10px; font-size:2.5em \"> CSS </p>\r\n";
26
27using (var document = new HTMLDocument(htmlContent, "."))
28{
29 // Save the HTML document to a file
30 document.Save(Path.Combine(OutputDir, "edit-external-css.html"));
31}
This example displays how to create CSS graphics from scratch. The visualization of the “edit-external-css.html” file is shown on the figure:
As was mentioned, the most common application of CSS is to style web pages written in HTML and other markup languages. But beyond the web design, you can use CSS to create some nice graphics, like the one we show you above. The critical concept of CSS drawing is to use border-radius, rotation and locating to create curves and shapes creatively.
You can download the complete examples and data files from GitHub.