Edit HTML Documents in Java

Aspose.HTML for Java represents HTML as a Document Object Model (DOM) tree. After creating or loading an HTMLDocument, you can find elements, create or remove nodes, update attributes and text, set innerHTML, inspect outerHTML, and change inline or internal CSS.

To edit HTML in Java, create or load an HTMLDocument, locate the required DOM node, apply changes through methods such as createElement(), appendChild(), setAttribute(), or setInnerHTML(), and call save() to write the updated HTML. Render or convert the document only when another output format is required.

HTML DOM for Document Editing

The DOM represents a document as a tree of nodes. The document is the root, elements define its structure, attributes describe elements, and text nodes contain character data. Aspose.HTML follows WHATWG DOM concepts, so Java code can navigate and update the document through standard DOM-style operations.

The main types used in this article are:

TypePurpose
DocumentRepresents the document tree and creates new nodes.
NodeProvides tree operations such as appending, inserting, replacing, and removing child nodes.
ElementRepresents an element and provides access to attributes and element markup.
TextRepresents textual content within the DOM.
HTMLElementProvides HTML-specific element features, including inline style access.

Common DOM Methods

MethodUse it to
getElementById()Find the first element with a specific id.
getElementsByTagName()Retrieve elements with the specified tag name.
createElement()Create an element that can be configured and inserted into the DOM.
createTextNode()Create a text node without parsing the text as HTML markup.
appendChild()Add a node as the last child of another node.
insertBefore()Insert a node before an existing child node.
removeChild()Remove a child node from its parent.
setAttribute()Add an attribute or replace its current value.
getAttribute()Read an attribute value.

Edit an HTML Document Tree

The following example creates an HTML document, adds an internal style rule and a paragraph, saves the edited HTML, and renders the same DOM to PDF:

  1. Create an empty HTMLDocument.
  2. Create a <style> element, add a CSS class rule, and append it to the document <head>.
  3. Create a paragraph, assign the CSS class, and append a text node.
  4. Add the paragraph to the document body.
  5. Save the edited document as HTML.
  6. Create a PdfDevice with a PDF output path and call renderTo() to render the document.
 1// Create HTML document using DOM methods and convert to PDF in Aspose.HTML for Java
 2
 3// Create an instance of the HTMLDocument class
 4HTMLDocument document = new HTMLDocument();
 5
 6// Create a style element and assign the green color for all elements with class-name equals "gr"
 7Element style = document.createElement("style");
 8style.setTextContent(".gr { color: green }");
 9
10// Find the document header element and append the style element to the header
11Element head = document.getElementsByTagName("head").get_Item(0);
12head.appendChild(style);
13
14// Create a paragraph element with class-name "gr"
15HTMLParagraphElement p = (HTMLParagraphElement) document.createElement("p");
16p.setClassName("gr");
17
18// Create a text node
19Text text = document.createTextNode("Hello, World!!");
20
21// Append the text node to the paragraph
22p.appendChild(text);
23
24// Append the paragraph to the document body element
25document.getBody().appendChild(p);
26
27// Save the HTML document to a file
28document.save("using-dom.html");
29
30// Create an instance of the PDF output device and render the document into this device
31PdfDevice device = new PdfDevice("using-dom.pdf");
32
33// Render HTML to PDF
34document.renderTo(device);

Before rendering, the saved HTML follows this structure:

1<html>
2    <head>
3        <style>.gr { color: green }</style>
4    </head>
5    <body>
6        <p class="gr">Hello, World!!</p>
7    </body>
8</html>

Edit Markup with setInnerHTML() and getOuterHTML()

Use setInnerHTML() to replace an element’s child markup. Use getOuterHTML() to read the serialized markup of the element itself together with its descendants.

  1. Create an empty HTMLDocument and print the initial root markup.
  2. Call setInnerHTML() on the document body with a paragraph fragment.
  3. Call getOuterHTML() on the document element to print the updated HTML.
 1// Edit HTML body content and print the updated outerHTML using Aspose.HTML for Java
 2
 3// Create an instance of the HTMLDocument class
 4HTMLDocument document = new HTMLDocument();
 5
 6// Write the content of the HTML document into the console output
 7System.out.println(document.getDocumentElement().getOuterHTML());
 8// @output: <html><head></head><body></body></html>
 9
10// Set the content of the <body> element
11document.getBody().setInnerHTML("<p>HTML is the standard markup language for Web pages.</p>");
12
13// Write the content of the HTML document into the console output
14System.out.println(document.getDocumentElement().getOuterHTML());
15// @output: <html><head></head><body><p>HTML is the standard markup language for Web pages.</p></body></html>

setInnerHTML() parses the supplied string as markup and replaces the element’s existing descendants. When input must be treated only as text, use setTextContent() or create a text node instead.

Edit CSS in an HTML Document

Aspose.HTML can update CSS before the document is saved or converted. Use an element’s style attribute for declarations that apply to one element, or add a <style> element to the document <head> for rules that can target multiple elements.

Edit Inline CSS

Inline CSS is stored in an element’s style attribute. The following example applies a font size, font family, and color to a paragraph, saves the edited HTML, and renders it to PDF:

  1. Create an HTMLDocument containing a paragraph.
  2. Retrieve the paragraph element.
  3. Set its style attribute with the required CSS declarations.
  4. Save the edited HTML document.
  5. Render the result through a PdfDevice that uses a .pdf output path.
 1// Edit inline CSS of an HTML element and render HTML to PDF using Aspose.HTML for Java
 2
 3// Create an instance of an HTML document with specified content
 4String content = "<p> Inline CSS </p>";
 5try (HTMLDocument document = new HTMLDocument(content, ".")) {
 6
 7    // Find the paragraph element to set a style attribute
 8    HTMLElement paragraph = (HTMLElement) document.getElementsByTagName("p").get_Item(0);
 9
10    // Set the style attribute
11    paragraph.setAttribute("style", "font-size: 250%; font-family: verdana; color: #cd66aa");
12
13    // Save the HTML document to a file
14    document.save("edit-inline-css.html");
15
16    // Create an instance of the PDF output device and render the document into this device
17    try (PdfDevice device = new PdfDevice("edit-inline-css.pdf")) {
18        document.renderTo(device);
19    }
20}

The rendered paragraph uses Verdana at 250% with the color #cd66aa:

Paragraph rendered with inline CSS in PDF

Edit Internal CSS

Internal CSS is defined in a <style> element, usually inside the document <head>. The following example adds two class rules and assigns them to paragraphs. It also updates individual declarations through each paragraph’s getStyle() object, producing inline styles that override conflicting class declarations:

  1. Create an HTMLDocument with two paragraphs.
  2. Create a <style> element containing .frame1 and .frame2 rules and append it to the document <head>.
  3. Assign the corresponding class name to each paragraph.
  4. Use getStyle() to set additional inline declarations on the paragraphs.
  5. Save the edited HTML and render it to PDF.
 1// Edit HTML with internal CSS using Java
 2
 3// Create an instance of an HTML document with specified content
 4String content = "<div><p>Internal CSS</p><p>An internal CSS is used to define a style for a single HTML page</p></div>";
 5try (HTMLDocument document = new HTMLDocument(content, ".")) {
 6
 7    // Create a style element with text content
 8    Element style = document.createElement("style");
 9    style.setTextContent(".frame1 { margin-top:50px; margin-left:50px; padding:20px; width:360px; height:90px; background-color:#a52a2a; font-family:verdana; color:#FFF5EE;} \r\n" +
10            ".frame2 { margin-top:-90px; margin-left:160px; text-align:center; padding:20px; width:360px; height:100px; background-color:#ADD8E6;}");
11
12    // Find the document header element and append the style element to the header
13    Element head = document.getElementsByTagName("head").get_Item(0);
14    head.appendChild(style);
15
16    // Find the first paragraph element to inspect the styles
17    HTMLElement paragraph = (HTMLElement) document.getElementsByTagName("p").get_Item(0);
18    paragraph.setClassName("frame1");
19
20    // Find the last paragraph element to inspect the styles
21    HTMLElement lastParagraph = (HTMLElement) document.getElementsByTagName("p").get_Item(document.getElementsByTagName("p").getLength() - 1);
22    lastParagraph.setClassName("frame2");
23
24    // Set a font-size to the first paragraph
25    paragraph.getStyle().setFontSize("250%");
26    paragraph.getStyle().setTextAlign("center");
27
28    // Set a color and font-size to the last paragraph
29    lastParagraph.getStyle().setColor("#434343");
30    lastParagraph.getStyle().setFontSize("150%");
31    lastParagraph.getStyle().setFontFamily("verdana");
32
33    // Save the HTML document to a file
34    document.save("edit-internal-css.html");
35
36    // Create an instance of the PDF output device and render the document on that device
37    try (PdfDevice device = new PdfDevice("edit-internal-css.pdf")) {
38
39        // Render HTML to PDF
40        document.renderTo(device);
41    }
42}

The rendered PDF shows both paragraphs with the internal class rules and their additional inline declarations applied:

Paragraphs rendered with internal and inline CSS in PDF

Common HTML Editing Issues

IssueCause and fix
An element lookup returns nullThe element does not exist or the identifier does not match. Check the source DOM before accessing or casting the result.
Existing child elements disappear after setInnerHTML()The method replaces all current descendants of the target element. Append nodes when existing children must be preserved.
Markup appears as visible textText content does not parse HTML tags. Use setInnerHTML() only for trusted markup that should become DOM nodes.
A CSS rule is not appliedCheck that the <style> element is in the document, the selector matches, and another declaration does not override it.
Changes are missing from the saved fileDOM changes remain in memory until save() is called. Save after completing the edits.

FAQ

How do I edit an HTML document in Java?

Create or load an HTMLDocument, find or create the required nodes, update their content, attributes, or CSS, and call save() to write the edited document.

What is the difference between innerHTML and outerHTML?

innerHTML represents the markup inside an element. outerHTML includes the element’s own start and end tags together with its descendant markup.

Should I use setTextContent() or setInnerHTML()?

Use setTextContent() when a value must remain plain text. Use setInnerHTML() when trusted markup should be parsed into elements and text nodes. Do not pass untrusted HTML to setInnerHTML() without appropriate validation or sanitization.

How do I add CSS to an HTML document?

Use setAttribute("style", declarations) or getStyle() for inline CSS. For document-level rules, create a <style> element, set its CSS text, and append it to the document <head>.

Does editing an HTMLDocument automatically update the source file?

No. DOM changes affect the in-memory document. Call save() with an output path to persist them.

Other Platforms

Related Articles