Removing commented lines from InnerText

c# html-agility-pack

Question

i'm currently using the below code which extracts the InnerText, however, what happens is i'm stuck with a bunch of comment out lines of html <-- how do I remove these using the code below?

HtmlWeb hwObject = new HtmlWeb();
HtmlAgilityPack.HtmlDocument htmldocObject = hwObject.Load(htmlURL);

foreach (var script in htmldocObject.DocumentNode.Descendants("script").ToArray())
    script.Remove();
HtmlNode body = htmldocObject.DocumentNode.SelectSingleNode("//body");
resultingHTML = body.InnerText.ToString();

Accepted Answer

This is probably a better answer:

public static void RemoveComments(HtmlNode node)
{
    foreach (var n in node.ChildNodes.ToArray())
        RemoveComments(n);
    if (node.NodeType == HtmlNodeType.Comment)
        node.Remove();
}

Popular Answer

Just filter the nodes by comment nodes and call remove on them.

var rootNode = doc.DocumentNode;
var query = rootNode.Descendants().OfType<HtmlCommentNode>().ToList();
foreach (var comment in query)
{
    comment.Remove();
}


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