以下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#代码解决这个问题?
使用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)
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)
| 归档时间: |
|
| 查看次数: |
5033 次 |
| 最近记录: |