编辑 HTML 文档
Aspose.HTML for Java 提供了强大的 API,可使用文档对象模型(DOM)以编程方式创建、修改和管理 HTML 文档。本文将演示如何编辑 HTML 文档,包括节点操作、设置样式以及使用内联和内部 CSS。
文档对象模型 – Document Object Model
文档对象模型(简称 DOM)是一种标准的跨平台编程应用程序接口,可帮助程序员访问和修改文档的部分内容。DOM 将文档结构定义为具有节点层次结构的树状结构,其中每个节点代表文档的一部分,如元素、类、标记、属性或文本。例如,图像或文本等每个部分都称为 “节点”。DOM 树是文档在内存中的表示方式或结构。换句话说,文档对象模型创建了一个逻辑文档结构,并定义了对象、属性、事件以及访问和修改它们的方法。DOM 在网络开发中被广泛用于管理网页元素和响应用户交互等任务。
用 Java 编辑 HTML
HTML DOM 将 HTML 元素定义为对象,提供了一系列属性和方法,您可以使用这些属性和方法来访问和管理这些元素。HTML 文档中的每个元素都由 DOM 树中的一个节点表示,每个节点都有自己的一套属性和方法。
正如我们在 创建 HTML 文档 一文中提到的, HTMLDocument 以及整个 DOM 都是基于 WHATWG DOM 标准实现的。因此,只要具备 HTML 和 JavaScript 语言的基础知识,就可以轻松使用 Aspose.HTML。 DOM package 具有以下基本数据类型:
| Class | 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. |
| 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. |
DOM 方法
HTML DOM 定义了一组可用于访问和控制所有 HTML 元素的方法。您可以使用这些方法执行各种任务,如创建、修改和删除元素,以及管理其属性和事件。下面简要列出了核心数据类型提供的实用 API 方法:
| 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(name) | The method must return the list of elements with the given name. |
| Document.createElement(localName) | The method creates the HTML element specified by tagName, 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 | Returns a fragment of markup contained within the element. |
使用我们的库,您可以通过多种方式编辑 HTML。您可以通过插入新节点、删除或编辑现有节点的内容来修改文档。如果需要创建新节点,则需要调用以下方法:
| 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 a new empty DocumentFragment into which DOM nodes can be added to build an offscreen DOM tree. |
| 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. |
创建新节点后,DOM 中有几种方法可以帮助您将节点插入文档树。下面列出了插入节点的最常用方法:
| 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 |
要从 HTML DOM 树中删除节点,请使用 Node.removeChild(child) 方法。
有关 DOM 软件包中的接口和方法的完整列表,请访问 API 参考源。
编辑 HTML 文档树
让我们看看如何使用 DOM 树和上述功能编辑 HTML 文档。请考虑创建和编辑 HTML 的简单步骤。下面的 Java 代码演示了如何从头开始创建 HTML 文档、添加样式化文本段落并保存结果:
- 使用
HTMLDocument()构造函数创建 HTML 文档实例。 - 使用
createElement(“style”) 方法创建一个
<style>元素。 - 调用
setTextContent()方法在样式元素中设置指定的文本内容。文本内容.gr { color: green }是一条 CSS 规则。它针对类名为"gr"的元素,并将其颜色设置为绿色。 - 使用
getElementsByTagName(name) 方法查找
<head>元素,并将样式元素作为子元素追加到 head 元素。 - 使用
createElement("p")和setClassName("gr")方法创建一个类名为"gr"的段落元素。 - 使用
createTextNode()和appendChild()方法创建一个文本节点,并将其添加为<p>元素的子节点。 - 将段落添加到文件正文中。
- 使用 save() 方法将 HTML 文档保存到文件中。
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.html");
32
33// Render HTML to PDF
34document.renderTo(device);生成的 HTML 文件如下所示:
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>使用 setInnerHTML() 和 getOuterHTML() 方法
DOM 对象为您提供了一个强大的工具来处理 HTML 文档。不过,有时使用
Class String 会更好。下面的示例演示了如何使用 Aspose.HTML Java 库创建 HTML 文档:使用 Element 类的 setInnerHTML() 和 getOuterHTML() 方法设置 body 元素的内容并将 HTML 文档输出到控制台:
- 使用 HTMLDocument() 构造函数创建一个 HTMLDocument 类实例。它会创建一个空的 HTML 文档。
- 要向控制台输出 HTML 文档的原始内容,请使用 getOuterHTML() 方法。由于文档最初是空的,因此输出将是 `。
- 使用
setInnerHTML() 方法设置
<body>元素的内容:在 body 元素中添加包含文本内容的 HTML<p>元素。 - 使用 getOuterHTML() 方法将更新后的 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>使用样式
内联 CSS
层叠样式表(CSS)是一种样式表语言,用于描述网页在浏览器中的外观。Aspose.HTML不仅支持开箱即用的CSS,而且还为您提供了在将HTML文档转换为其他格式之前即时处理文档样式的工具。
使用 HTML 标签内的样式属性编写 CSS 时,称为 “内联样式 CSS”。内联 CSS 可让你一次对一个 HTML 元素应用一个单独的样式。您可以使用 style 属性为 HTML 元素设置 CSS,并在其中定义 CSS 属性。在下面的代码片段中,你可以看到如何为 HTML <p>元素指定 CSS 样式属性:
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>";
5HTMLDocument document = new HTMLDocument(content, ".");
6
7// Find the paragraph element to set a style attribute
8HTMLElement paragraph = (HTMLElement) document.getElementsByTagName("p").get_Item(0);
9
10// Set the style attribute
11paragraph.setAttribute("style", "font-size: 250%; font-family: verdana; color: #cd66aa");
12
13// Save the HTML document to a file
14document.save("edit-inline-css.html");
15
16// Create an instance of the PDF output device and render the document into this device
17PdfDevice device = new PdfDevice("edit-inline-css.html");
18document.renderTo(device);在本例中,颜色、字体大小和字体家族适用于 <p> 元素。呈现的 pdf 页面片段如下:

外部 CSS
在文档的<head>中添加一个<style>元素,用于全局样式:
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>";
5HTMLDocument document = new HTMLDocument(content, ".");
6
7// Create a style element with text content
8Element style = document.createElement("style");
9style.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
13Element head = document.getElementsByTagName("head").get_Item(0);
14head.appendChild(style);
15
16// Find the first paragraph element to inspect the styles
17HTMLElement paragraph = (HTMLElement) document.getElementsByTagName("p").get_Item(0);
18paragraph.setClassName("frame1");
19
20// Find the last paragraph element to inspect the styles
21HTMLElement lastParagraph = (HTMLElement) document.getElementsByTagName("p").get_Item(document.getElementsByTagName("p").getLength() - 1);
22lastParagraph.setClassName("frame2");
23
24// Set a font-size to the first paragraph
25paragraph.getStyle().setFontSize("250%");
26paragraph.getStyle().setTextAlign("center");
27
28// Set a color and font-size to the last paragraph
29lastParagraph.getStyle().setColor("#434343");
30lastParagraph.getStyle().setFontSize("150%");
31lastParagraph.getStyle().setFontFamily("verdana");
32
33// Save the HTML document to a file
34document.save("edit-internal-css.html");
35
36// Create an instance of the PDF output device and render the document on that device
37PdfDevice device = new PdfDevice("edit-internal-css.html");
38
39// Render HTML to PDF
40document.renderTo(device);图中展示了 “edit-internal-css.pdf “文件的渲染片段:

结论
Aspose.HTML for Java 为编辑 HTML 文档提供了强大而灵活的 API。您可以利用 DOM 以编程方式创建、操作和渲染网页内容。Aspose.HTML for Java 遵循现代标准并具有高级功能,可简化复杂的网络开发任务。利用这些功能,您可以有效地管理和定制 HTML 内容,以满足您的特定需求。
您可以从 GitHub 下载完整的示例和数据文件。