如何使用HTML敏捷包注释掉html文档中的所有脚本标记

Zug*_*alt 3 c# comments html-agility-pack

我想要注释掉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();
            }
Run Code Online (Sandbox Code Playgroud)

请注意,我可以使用html上的替换函数来执行此操作,但我认为它不会那么强大:

domHtml = domHtml.Replace("<script", "<!-- <script");
domHtml = domHtml.Replace("</script>", "</script> -->");
Run Code Online (Sandbox Code Playgroud)

Yur*_*kiy 5

试试这个:

foreach (var scriptTag in htmlDocument.DocumentNode.SelectNodes("//script"))
        {
            var commentedScript = HtmlTextNode.CreateNode(string.Format("<!--{0}-->", scriptTag.OuterHtml));
            scriptTag.ParentNode.ReplaceChild(commentedScript, scriptTag);
        }
Run Code Online (Sandbox Code Playgroud)