Removing HTML Comments

2019-02-16 23:26发布

问题:

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