C# How to delete XML/HTML comments with regular expression

前端 未结 4 1277
说谎
说谎 2020-12-09 04:17

The fragment below doesn\'t work for me.

fragment = Regex.Replace(fragment, \"\", String.Empty , RegexOptions.Multiline  );
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 05:13

    Please don't use regular expressions to work with markup languages - you need to use a better tool that is built for that kind of job.

    Use the Html Agiliy Pack instead. I even found this article in which a reader (named Simon Mourier) comments with a function that uses the Html Agility Pack to remove comments from a document:

    Simon Mourier said:

    This is a sample code to remove comments:

    static void Main(string[] args) 
    { 
      HtmlDocument doc = new HtmlDocument(); 
      doc.Load("filewithcomments.htm"); 
      doc.Save(Console.Out); // show before 
      RemoveComments(doc.DocumentNode); 
      doc.Save(Console.Out); // show after 
    } 
    
    static void RemoveComments(HtmlNode node)
    {
        if (!node.HasChildNodes)
        {
            return;
        }
    
        for (int i=0; i

提交回复
热议问题