user222427
user222427

Reputation:

Removing commented lines from InnerText

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();

Upvotes: 2

Views: 1525

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134621

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();
}

Upvotes: 3

M.Babcock
M.Babcock

Reputation: 18965

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();
}

Upvotes: 2

Related Questions