【问题标题】:Removing HTML Comments删除 HTML 注释
【发布时间】:2011-07-23 08:40:07
【问题描述】:

如何从 HTML 文件中删除评论?

它们可能只占一行,但我相信我会遇到评论可能跨越多行的情况:

<!-- Single line comment. -->

<!-- Multi-
ple line comment.
Lots      '""' '  "  ` ~ |}{556             of      !@#$%^&*())        lines
in
this
comme-
nt! -->

【问题讨论】:

  • 如果您的目标是压缩您的文件,请在 Google 上“缩小 HTML”以获取可以添加到工作流程中的各种解决方案。

标签: c# .net html winforms comments


【解决方案1】:

这个功能稍作调整应该可以工作:-

 private string RemoveHTMLComments(string input)
    {
        string output = string.Empty;
        string[] temp = System.Text.RegularExpressions.Regex.Split(input, "<!--");
        foreach (string s in temp)
        {
            string str = string.Empty;
            if (!s.Contains("-->"))
            {
                str = s;
            }
            else
            {
                str = s.Substring(s.IndexOf("-->") + 3);
            }
            if (str.Trim() != string.Empty)
            {
                output = output + str.Trim();
            }
        }
        return output;
    }

不确定它是否是最好的解决方案...

【讨论】:

    【解决方案2】:

    您可以使用Html Agility Pack .NET 库。这是一篇解释如何在 SO 上使用它的文章:How to use HTML Agility pack

    这是删除 cmets 的 C# 代码:

        HtmlDocument doc = new HtmlDocument();
        doc.Load("yourFile.htm");
    
        // get all comment nodes using XPATH
        foreach (HtmlNode comment in doc.DocumentNode.SelectNodes("//comment()"))
        {
            comment.ParentNode.RemoveChild(comment);
        }
        doc.Save(Console.Out); // displays doc w/o comments on console
    

    【讨论】:

    【解决方案3】:

    不是最好的解决方案,而是一个简单的通过算法。应该做的伎俩

    List<string> output = new List<string>();
    
    bool flag = true;
    foreach ( string line in System.IO.File.ReadAllLines( "MyFile.html" )) {
    
        int index = line.IndexOf( "<!--" );
    
        if ( index > 0 )) {
            output.Add( line.Substring( 0, index ));
            flag = false;
        }
    
        if ( flag ) {
            output.Add( line );
        }
    
        if ( line.Contains( "-->" )) {
           output.Add( line.Substring( line.IndexOf( "-->" ) + 3 )); 
           flag = true;
       }
    }
    
    System.IO.File.WriteAllLines( "MyOutput.html", output ); 
    

    【讨论】:

    • 啊,确实如此……我可以改变它,也许应该……嗯,很好,很好
    • 感谢 Akash Kava - 尽管这样做很烦人,但修复它是正确的。
    猜你喜欢
    • 2012-04-04
    • 2016-11-05
    • 1970-01-01
    • 2016-09-05
    • 2018-07-01
    • 2014-04-21
    • 2012-07-05
    • 2014-11-16
    相关资源
    最近更新 更多