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

时间:2011-07-08 15:57:38

标签: c# html-agility-pack comments

我想注释掉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> -->");

2 个答案:

答案 0 :(得分:5)

试试这个:

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

答案 1 :(得分:0)

请参阅此SO帖子 - 利用HTML Agility Pack的Linq查询支持的非常干净的解决方案: htmlagilitypack - remove script and style?