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

4

我希望能够从HTML中去除诸如

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


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

如何使用HTMLAgilityPack在C#中实现这个功能?

我正在使用:

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

对于普通标签。


我甚至不确定来自Microsoft Word的条件语句片段是否为HtmlNodeType.Comment。 - bcm
2个回答

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

        }
或者使用有趣的小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();

更简单的方法(忘记了我们可以使用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();

1
为了寻找更好的编码方法来完成相同的任务,点赞。 - bcm

0

马克,我加入了你第三个例子以供参考:

public static string CleanUpRteOutput(this string s)
        {
            if (s != null)
            {
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(s);
                RemoveTag(doc, "script");
                RemoveTag(doc, "link");
                RemoveTag(doc, "style");
                RemoveTag(doc, "meta");
                RemoveTag(doc, "comment");
...

还有removeTag函数:

static void RemoveTag(HtmlAgilityPack.HtmlDocument doc, string tag)
        {
            foreach (var n in doc.DocumentNode.SelectNodes("//" + tag) ?? new HtmlAgilityPack.HtmlNodeCollection(doc.DocumentNode))
                n.Remove(); 
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接