作者: littleboy 2022-09-12 11:53:21

CSharp编辑Html

创建

程序的执行从 Main 方法开始。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 此代码示例演示如何创建 HTML 文档。

// 创建一个空的 HTML 文档
var document = new HTMLDocument();

// 添加标题
// 1.创建一个标题元素
var h2 = (HTMLHeadingElement)document.CreateElement("h2");

// 2.创建一个文本元素
var text = document.CreateTextNode("This is Sample Heading!");

// 3.在标题中添加文本元素
h2.AppendChild(text);

// 4. 添加标题 to the document
document.Body.AppendChild(h2);

// 添加段落
// 1.创建段落元素
var p = (HTMLParagraphElement)document.CreateElement("p");

// 2.设置自定义属性
p.SetAttribute("id", "first-paragraph");

// 3.创建文本节点
var paraText = document.CreateTextNode("This is first paragraph. ");

// 4.给段落添加文字
p.AppendChild(paraText);

// 5.将段落附加到文件正文
document.Body.AppendChild(p);

// 添加有序列表
// 创建段落元素
var list = (HTMLOListElement)document.CreateElement("ol");

// 添加第 1 项
var item1 = (HTMLLIElement)document.CreateElement("li");
item1.AppendChild(document.CreateTextNode("First list item."));

// 添加第 2 项
var item2 = (HTMLLIElement)document.CreateElement("li");
item2.AppendChild(document.CreateTextNode("Second list item."));

// 将 li 项添加到列表中
list.AppendChild(item1);
list.AppendChild(item2);

// 将列表附加到文档正文
document.Body.AppendChild(list);

// 将 HTML 文档保存到文件
document.Save(@"C:\Files\html\create-new-document.html");

读取

1
2
3
4
5
6
7
8
9
// 此代码示例演示如何读取 HTML 文件
// 准备文档保存的输出路径
string documentPath = @"C:\Files\html\create-new-document.html";

// 加载 HTML 文件
var document = new HTMLDocument(documentPath);

// 将文档内容写入输出流
Console.WriteLine(document.DocumentElement.OuterHTML);

编辑

参考

C# 读取 HTML 文件 | C# 创建 HTML 文件 |编辑 HTML 文件 C# (aspose.com)