如何使用HTMLAgilityPack选择HtmlNodeType.Comment的节点类型

bcm*_*bcm 3 c# html-agility-pack

我想从html中删除像

<!--[if gte mso 9]>
...
<![endif]-->


<!--[if gte mso 10]>
...
<![endif]-->
Run Code Online (Sandbox Code Playgroud)

如何使用HTMLAgilityPack在C#中执行此操作?

我正在使用

static void RemoveTag(HtmlNode node, string tag)
        {
            var nodeCollection = node.SelectNodes("//"+ tag );
            if(nodeCollection!=null)
                foreach (HtmlNode nodeTag in nodeCollection)
                {
                    nodeTag.Remove();
                }
        }
Run Code Online (Sandbox Code Playgroud)

对于普通标签.

mpe*_*pen 10

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


        static void Main(string[] args)
        {
            var doc = new HtmlDocument();
            string html = @"<!--[if gte mso 9]>
...
<![endif]-->

<body>
    <span>
        <!-- comment -->
    </span>
    <!-- another comment -->
</body>

<!--[if gte mso 10]>
...
<![endif]-->";
            doc.LoadHtml(html);

            RemoveComments(doc.DocumentNode);
            Console.WriteLine(doc.DocumentNode.OuterHtml);
            Console.ReadLine();

        }
Run Code Online (Sandbox Code Playgroud)

或者一个有趣的小LINQ风格:

public static IEnumerable<HtmlNode> Walk(HtmlNode node)
{
    yield return node;
    foreach (var child in node.ChildNodes)
        foreach (var x in Walk(child))
            yield return x;
}

...

foreach (var n in Walk(doc.DocumentNode).OfType<HtmlCommentNode>().ToArray())
    n.Remove();
Run Code Online (Sandbox Code Playgroud)

更容易(忘了我们可以用xpath来查找注释节点)

    var doc = new HtmlDocument();
    string html = @"
<!--[if gte mso 9]>
...
<![endif]-->

<body>
<span>
<!-- comment -->
</span>
<!-- another comment -->
</body>

<!--[if gte mso 10]>
...
<![endif]-->";
    doc.LoadHtml(html);
    foreach (var n in doc.DocumentNode.SelectNodes("//comment()") ?? new HtmlNodeCollection(doc.DocumentNode))
        n.Remove();
Run Code Online (Sandbox Code Playgroud)