C# 如何使用html agility pack注释掉html文档中的所有脚本标记

C# 如何使用html agility pack注释掉html文档中的所有脚本标记,c#,html-agility-pack,comments,C#,Html Agility Pack,Comments,我想注释掉HtmlDocument中的所有脚本标记。这样,当我呈现文档时,脚本不会被执行,但是我们仍然可以看到那里有什么。不幸的是,我目前的方法失败了: foreach (var scriptTag in htmlDocument.DocumentNode.SelectNodes("//script")) { var commentedScript = new HtmlNode(HtmlNodeType.Comment, htmlDocum

我想注释掉HtmlDocument中的所有脚本标记。这样,当我呈现文档时,脚本不会被执行,但是我们仍然可以看到那里有什么。不幸的是,我目前的方法失败了:

foreach (var scriptTag in htmlDocument.DocumentNode.SelectNodes("//script"))
            {
                var commentedScript = new HtmlNode(HtmlNodeType.Comment, htmlDocument, 0) { InnerHtml = scriptTag.ToString() };
                scriptTag.ParentNode.AppendChild(commentedScript);
                scriptTag.Remove();
            }
请注意,我可以使用html上的替换函数来实现这一点,但我认为它不会那么健壮:

domHtml = domHtml.Replace("<script", "<!-- <script");
domHtml = domHtml.Replace("</script>", "</script> -->");
domHtml=domHtml.Replace(“”);
试试这个:

foreach (var scriptTag in htmlDocument.DocumentNode.SelectNodes("//script"))
        {
            var commentedScript = HtmlTextNode.CreateNode(string.Format("<!--{0}-->", scriptTag.OuterHtml));
            scriptTag.ParentNode.ReplaceChild(commentedScript, scriptTag);
        }
foreach(htmlDocument.DocumentNode.SelectNodes(“//脚本”)中的var scriptTag)
{
var commentedScript=HtmlTextNode.CreateNode(string.Format(“,scriptTag.OuterHtml));
scriptTag.ParentNode.ReplaceChild(commentedScript,scriptTag);
}

请参考此使用HTML Agility Pack的Linq查询支持的非常干净的解决方案:

如何将语言属性更改为浏览器无法理解的内容?