Removing HTML Comments

杀马特。学长 韩版系。学妹 提交于 2019-12-09 03:12:54

问题


How would one go about removing Comments from HTML files?

They may only take up a single line, however I'm sure I'll run into cases where a comment may span across multiple lines:

<!-- Single line comment. -->

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

回答1:


You could use the Html Agility Pack .NET library. Here is an article that explains how to use it on SO: How to use HTML Agility pack

This is the C# code to remove comments:

    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



回答2:


This function with minor tweaks should work :-

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

Not sure if its the best solution...




回答3:


Not the best solution out there but a simple on pass algo. should do the trick

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


来源:https://stackoverflow.com/questions/5440392/removing-html-comments

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