使用 XPath 查找和替换整个 HTML 文档中的关键字
本文关键字:文档 HTML 关键字 XPath 查找 替换 使用 | 更新日期: 2023-09-27 18:32:52
我需要搜索整个HTML文档并突出显示我搜索的关键字。我正在使用 C# 和 XPath 作为解决方案。我想我有点解决方案,但输出不是我想要的。
static string keyword = "red";
static void Main(string[] args)
{
string htmlString = @"<html>
<head>
<title>HTML sample page</title>
</head>
<body>
<div><div>This is inside div red paragraph</div></div>
<p>This is a red paragraph</p>
<p>This is a tes paragraph</p>
<p>This is a test paragraph</p>
<p>This is a paragraph red </p>
</body>
</html>";
XmlDocument htmlDocument = new XmlDocument();
htmlDocument.Load(new StringReader(htmlString));
foreach (XmlNode node in htmlDocument.SelectNodes("//*[contains(., 'red')]"))
{
node.InnerText = node.InnerText.Replace(keyword, "highlight" + keyword + "highlight");
}
Console.WriteLine(htmlDocument.InnerXml);
}
我得到的输出如下所示:
<html>HTML sample pageThis is inside div highlightredhighlight paragraphThis is a highlightredhighlight paragraphThis is a tes paragraphThis is a test paragraphThis is a paragraph highlightredhighlight </html>
输出似乎摆脱了除 html 标签之外的所有其他标签。我做错了什么吗?
你得到的第一个匹配项是 html 标签,因为它包含红色!!因此,您只需将其所有内容替换为带有额外突出显示词的文本即可。
此外,如果您确实需要突出显示文本,则需要拆分文本并在其中插入一个红色(或类似的东西)节点。
请尝试这个
foreach (XmlNode node in htmlDocument.SelectNodes("//*[contains(text(), 'red')]"))
dotnetfiddle: https://dotnetfiddle.net/iqBxeJ