How to use Agility Pack to remove comments from HTML without loosing the DOCTYPE?

html-agility-pack

Question

I am trying to remove unnecessary content from HTML. Specifically I want to remove comments. I found a pretty good solution (Grabbing meta-tags and comments using HTML Agility Pack) however the DOCTYPE is treated as a comment and therefore removed along with the comments. How can I improve the code below to make sure the DOCTYPE is preserved?

var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
var nodes = htmlDoc.DocumentNode.SelectNodes("//comment()");
if (nodes != null)
{
    foreach (HtmlNode comment in nodes)
    {
        comment.ParentNode.RemoveChild(comment);
    }
}
1
10
5/23/2017 12:00:31 PM

Accepted Answer

Check that comment does not start with DOCTYPE

  foreach (var comment in nodes)
  {
     if (!comment.InnerText.StartsWith("DOCTYPE"))
         comment.ParentNode.RemoveChild(comment);
  }
9
7/4/2011 5:20:12 AM

Popular Answer

doc.DocumentNode.Descendants()
 .Where(n => n.NodeType == HtmlAgilityPack.HtmlNodeType.Comment)
 .ToList()
 .ForEach(n => n.Remove());

this will strip off all comments from the document



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow