如何删除c#中标签之间的文本?

til*_*lak 2 c#

以下HTML语句存储在字符串中.我需要删除HTML标记之间书写文字 <style></style>

<html> <head><style type="text/css">
        @font-face { 
            font-family: "tunga";
            src: url(tunga.TTF); 
        }

        body {              
            font-family:"tunga";
            padding:0;
            margin: 0;
        }


        table {
            font-family:"tunga";
            padding:0;
        }

        a {
            text-decoration:none
        }

    </style></head>  <body marginwidth="0" marginheight="0" leftmargin="10" topmargin="0" >
    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

如何使用c#代码解决这个问题?

Céd*_*non 7

使用HtmlAgilityPack加载Html文件.

打开文件:

HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(myHtmlString);
Run Code Online (Sandbox Code Playgroud)

然后删除节点:

foreach(var descendant in htmlDocument.DocumentNode.Descendants("style").ToList())
    descendant.Remove()
Run Code Online (Sandbox Code Playgroud)

然后获取代表HTML文件的字符串:

string htmlWithoutStyle = htmlDocument.DocumentNode.OuterHtml;
Run Code Online (Sandbox Code Playgroud)

  • @AshBurlaczenko Html解析并不像你想象的那么简单. (6认同)
  • @AshBurlaczenko所以你宁愿写冗长的字符串比较锅炉板代码? (3认同)
  • 没有必要为此导入额外的库. (2认同)

vik*_*kas 4

string str = "<html> <head><style type='text/css'> jhiun  </style></head> </html>";
            Console.WriteLine(str);
            string strToRemove = str.Substring(str.IndexOf("<style"), str.IndexOf("</style>") - str.IndexOf("<style") + 8); 
            Console.WriteLine(str.Replace(strToRemove,""));
            Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)