如何在 C# 中使用 CSS 选择器 – QuerySelector、QuerySelectorAll
CSS 选择器用于选择要设置样式的 HTML 元素,并应用一组 CSS 规则。此外,你还可以使用 CSS 选择器浏览 HTML 文档,提取所选元素的信息或对其进行编辑。CSS 选择器用于声明样式适用于哪些标记元素,这是一种匹配表达式。Aspose.HTML API 允许您根据 CSS 选择器语法创建搜索模式,以匹配文档树中的元素。
在本文中,您将了解如何使用
Document 类的
QuerySelector(selector
) 和
QuerySelectorAll(selector
) 方法有效地应用选择器来选择要样式化的元素。这些方法允许您通过与选择器匹配,快速、轻松地从 DOM 中检索元素节点。您可以通过类、id 或名称或任何复杂的 CSS 选择器来选择元素。
有关如何有效应用选择器来选择想要样式化的元素的更多信息,请访问文章 CSS Selectors。您将学习基本选择器、组合选择器、属性选择器、组选择器和伪选择器。
通过 QuerySelector() 浏览 HTML
QuerySelector() 方法用于查询与 CSS 选择器匹配的 DOM 元素。它会返回文档中第一个匹配指定选择器的元素。如果找不到匹配元素,则返回 null。在下面的示例中,我们使用 CSS 元素选择器查找第一个段落元素,并将其内容输出到控制台:
C# 示例
1// Extract HTML content using CSS selector
2
3// Prepare path to source HTML file
4string documentPath = Path.Combine(DataDir, "queryselector.html");
5
6// Create an instance of an HTML document
7HTMLDocument document = new HTMLDocument(documentPath);
8
9// Here we create a CSS Selector that extracts the first paragraph element
10Element element = document.QuerySelector("p");
11
12// Print content of the first paragraph
13Console.WriteLine(element.InnerHTML);
14// output: The QuerySelector() method returns the first element in the document that matches the specified selector.
15
16// Set style attribute with properties for the selected element
17element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe;");
18
19// Save the HTML document to a file
20document.Save(Path.Combine(OutputDir, "queryselector-p.html"));
此外,在 C# 示例中,选定元素的文本颜色和背景颜色都发生了变化。下一个 HTML 代码示例包括使用 querySelector(“p”) 方法的 JavaScript:
JavaScript querySelector()
1<html>
2<head>
3</head>
4 <body>
5 <h1>QuerySelector() Method</h1>
6 <p>The QuerySelector() method returns the first element in the document that matches the specified selector.</p>
7 <p>CSS Selectors are used to declare which of the markup elements a style applies to, a kind of match expression.</p>
8 </body>
9 <script>
10 // Create a CSS Selector that selects the first paragraph element
11 var element = document.querySelector("p");
12
13 // Set style attribute with properties for the selected element
14 element.setAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe");
15 </script>
16</html>
通过 QuerySelector() 为选定元素添加样式
QuerySelector() 方法接受选择器来确定应返回的元素,并返回节点子树中第一个匹配的元素。如果找不到匹配的节点,则返回 null。在下面的 C# 示例中,QuerySelector() 方法的参数是 div:last-child
选择器,表示选择其父节点的最后一个子节点 <div>
。 注意:QuerySelector() 方法返回与选择器匹配的个元素。
C# 示例
1// Select and style HTML element with C# CSS selector
2
3// Prepare output path for HTML document saving
4string savePath = Path.Combine(OutputDir, "css-celector-style.html");
5
6// Prepare path to source HTML file
7string documentPath = Path.Combine(DataDir, "nature.html");
8
9// Create an instance of an HTML document
10HTMLDocument document = new HTMLDocument(documentPath);
11
12// Create a CSS Selector that selects <div> element that is the last child of its parent
13Element element = document.QuerySelector("div:last-child");
14
15// Set the style attribute with properties for the selected element
16element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe; text-align:center");
17
18// Save the HTML document to a file
19document.Save(Path.Combine(savePath));
JavaScript querySelector()
1<script>
2 // Create a CSS Selector that selects <div> element that is the 2-d child of its parent
3 var element = document.querySelector("div:nth-child(2)");
4
5 // Set style attribute with properties for the selected element
6 element.setAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe; text-align:center");
7</script>
让我们看看使用 QuerySelector() 方法对符合选择器的 <div>
元素重新样式化后的结果:a) 原始 HTML 文档的图像;b) 更改样式后 HTML 文档的图像。
通过 QuerySelectorAll() 为选定元素添加样式
如果想获得与指定选择器匹配的所有元素的列表,应使用 QuerySelectorAll() 方法。
在下面的示例中,我们使用
QuerySelectorAll() 方法浏览 HTML 文档并搜索所需的元素。该方法将查询选择器作为参数,并返回一个包含所有符合指定选择器的元素的 NodeList。我们选择所有 class
属性等于 square2
的元素,并为它们重新着色:
C# 示例
1// Apply background color to elements by class using C#
2
3// Prepare output path for HTML document saving
4string savePath = Path.Combine(OutputDir, "css-selector-color.html");
5
6// Prepare path to source HTML file
7string documentPath = Path.Combine(DataDir, "spring.html");
8
9// Create an instance of an HTML document
10HTMLDocument document = new HTMLDocument(documentPath);
11
12// Here we create a CSS Selector that extracts all elements whose 'class' attribute equals 'square2'
13NodeList elements = document.QuerySelectorAll(".square2");
14
15// Iterate over the resulted list of elements
16foreach (HTMLElement element in elements)
17{
18 // Set the style attribute with new background-color property
19 element.Style.BackgroundColor = "#b0d7fb";
20}
21
22// Save the HTML document to a file
23document.Save(Path.Combine(savePath));
JavaScript querySelectorAll()
1<script>
2 // Create a CSS Selector that extracts all elements whose 'class' attribute equals 'square2'
3 var elements = document.querySelectorAll(".square2");
4
5 // Iterate over the resulted list of elements and set style background-color property
6 for(var i = 0; i < elements.length; i++){
7 document.querySelectorAll(".square2")[i].style.backgroundColor = "#b0d7fb";
8 }
9</script>
所有带有 class="square2"
的元素都被重新着色。图中显示了对源文件
spring.html (a) 应用 QuerySelectorAll() 方法 (b) 的结果:
Aspose.HTML 提供免费的 HTML 网络应用程序,是转换器、合并器、搜索引擎优化工具、HTML 代码生成器、URL 工具等的在线集合。这些应用程序可在任何装有网络浏览器的操作系统上运行,无需安装任何其他软件。它是一种快速、简便的方法,能有效解决与 HTML 相关的任务。