创建 HTML 文档 – 用 C# 创建或加载 HTML
本文将详细介绍如何创建 HTML 文档。Aspose.HTML for .NET API 提供了 HTMLDocument类,该类是 HTML 层次结构的根,保存着整个内容。
HTML 文件
HTMLDocument
是 Aspose.HTML for .NET 库的起点。您可以使用 HTMLDocument 类将 HTML 页面加载到**文档对象模型(DOM)**中,然后以编程方式读取、修改文档树、添加和删除节点、更改文档中的节点属性,正如官方规范中所描述的那样。
HTMLDocument类提供了HTML DOM的内存表示,完全基于 W3C DOM和 WHATWG DOM规范,许多现代浏览器都支持这些规范。如果您熟悉 WHATWG DOM、 WHATWG HTML和 JavaScript标准,您会发现使用 Aspose.HTML for .NET 相当方便。否则,您可以访问 www.w3schools.com,在那里您可以找到大量有关如何处理 HTML 文档的示例和教程。
HTML 文档可以从头开始创建,比如创建一个带有 HTML 结构的空文档、从字符串中创建、从内存流中创建、从文件或 URL 中加载。 HTMLDocument有几个重载构造函数,允许你创建或加载 HTML 文档。
创建一个空的 HTML 文档
一旦创建了文档对象,以后就可以用 HTML 元素来填充它。下面的代码片段展示了如何使用默认的 HTMLDocument() 构造函数来创建一个空的 HTML 文档并将其保存到文件中。
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}
创建完成后,文件 create-empty-document.html 将显示初始文档结构:空文档包括 <html>
,<head>
和 <body>
等元素。有关保存 HTML 文件的更多详情,请参阅
Save HTML Document 一文。
创建新的 HTML 文档
如果您想以编程方式从头开始生成文档,请使用以下代码片段中指定的不带参数的构造函数:
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}
在新文档中,我们使用 CreateTextNode() 方法创建了一个文本节点,给定了指定的字符串,并使用 AppendChild() 方法将其添加到正文元素中。
编辑 HTML 文件的方法详见 编辑 HTML 文档 一文。
从文件加载
以下代码片段展示了如何从现有文件加载 HTMLDocument :
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}
在上面的示例中,HTML 文档是使用
HTMLDocument (string
) 构造函数从文件中加载的。如果您需要从磁盘加载一个现有的 HTML 文件,并对其进行处理和保存,那么下面的代码片段将对您有所帮助。
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}
从 URL 加载
在用户的本地设备上选择文件并与之交互的功能是互联网最常用的功能之一。在下一个代码片段中,您可以看到如何将网页加载到 HTMLDocument 中。
如果您传递了一个错误的 URL,而该 URL 目前无法访问,那么程序库会抛出带有专门代码 NetworkError 的 DOMException,通知您所选资源无法找到。
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}
在上面的示例中,我们指定从 URL 加载 document.html 文件。
从 HTML 代码加载
如果将 HTML 代码准备为内存中的 System.String 或 System.IO.Stream 对象,则无需将其保存到文件中,只需将 HTML 代码传入专门的构造函数即可。
如果您的 HTML 代码中包含链接资源(样式、脚本、图片等),则需要向文档的构造函数传递一个有效的 baseUrl 参数。它将用于在文档加载过程中解析资源的位置。
从字符串加载
您可以使用
HTMLDocument (string, string
) 构造函数从字符串内容创建文档。如果您想在代码中直接从用户字符串创建文档并保存到文件中,下面的示例可以帮到您:我们创建了一个包含 “Hello, World!“文本的 HTML 文档。
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}
从流加载
要从数据流中创建 HTML 文档,可以使用
HTMLDocument(stream, string
) 构造函数:
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}
SVG 文档
由于可缩放矢量图形(SVG)是 W3C标准的一部分,可以嵌入到 HTMLDocument中,因此我们实现了 SVGDocument及其所有功能。我们的实现基于官方 SVG2 规范,因此您可以按照官方的描述加载、读取和操作 SVG 文档。
由于 SVGDocument 和 HTMLDocument 基于相同的 WHATWG DOM标准,因此这两种文档的所有操作(如加载、读取、编辑、转换和保存)都是相似的。因此,所有在 HTMLDocument 中可以看到的操作示例也适用于 SVGDocument。
你可以使用SVGDocument(string, string)
构造函数从字符串内容创建文档。如果你想从内存中的
System.String 变量加载 SVG 文档,并且不需要将其保存到文件中,下面的示例将向你展示如何实现:
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}
在上面的示例中,我们制作了一个 SVG 文档,其中包含一个半径为 40 像素的圆。您可以在 如何使用 Aspose.SVG API章节中了解更多有关使用 SVG 文档的信息。
MHTML 文档
MHTML 是 MIME 封装 HTML 文档的缩写。MHTML 文件是一个包含网页所有内容的归档文件。它存储网页的 HTML 以及网页上的相关资源,包括 CSS、JavaScript、图像和音频文件。它是一种创建网页存档的专门格式,网页开发人员主要使用 MHTML 文件保存网页的当前状态,以便存档。Aspose.HTML for .NET 库支持这种格式,但有一些限制。我们只支持从 MHTML 到支持的输出格式的渲染操作。有关详细信息,请阅读 格式之间的转换一文。
EPUB 文档
EPUB 是一种受大多数电子阅读器支持的格式,与智能手机、平板电脑和电脑等大多数阅读设备兼容。对于代表电子出版物格式的EPUB格式,我们有与MHTML相同的限制。我们只支持从 EPUB 到支持的输出格式的渲染操作。更多详情,请阅读 格式间转换一文。
异步操作
我们意识到,加载文档可能是一项资源密集型操作,因为这不仅需要加载文档本身,还需要加载所有链接资源和处理所有脚本。因此,在下面的代码片段中,我们将向您展示如何使用异步操作,在不阻塞主线程的情况下加载 HTMLDocument 文件:
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);
ReadyStateChange 并不是唯一一个可以用来处理异步加载操作的事件,你还可以订阅 Load 事件,如下所示:
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);
您可以从 GitHub 下载完整的示例和数据文件。