Removing commented lines from InnerText

こ雲淡風輕ζ 提交于 2021-02-10 12:14:30

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/9106177/removing-commented-lines-from-innertext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!