删除HTML评论

8 .net html c# comments winforms

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

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

<!-- Single line comment. -->

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

Sim*_*ier 14

您可以使用Html Agility Pack .NET库.这篇文章解释了如何在SO上使用它:如何使用HTML Agility包

这是删除注释的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
Run Code Online (Sandbox Code Playgroud)

  • 只是在这里指出(根据 http://meta.stackexchange.com/questions/156184 的要求),Simon 推荐的库是他自己的作者之一。 (2认同)

zel*_*lio 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 ); 
Run Code Online (Sandbox Code Playgroud)