【问题标题】:Remove Unnecessary Tags from Html string in c# [duplicate]从C#中的Html字符串中删除不必要的标签[重复]
【发布时间】:2020-09-27 01:15:50
【问题描述】:

我正在从系统获取这个 Html 字符串

<h1>PDF Attachment</h1>
<h1 style="color: rgb(51, 51, 51); text-align: center;">
  <p style="font-size: 14px; font-weight: 400; text-align: justify;">Your service detail are following</p><p style="font-size: 14px; font-weight: 400; text-align: justify;">
    <table>
      <tr><td></td></tr>
    </table>&nbsp;
    <br>
 </p>
 <p style="font-size: 14px; font-weight: 400; text-align: justify;">  
   <br>
 </p>
</h1>

我在这个字符串中有两个 h1 标签。我想删除使用“table”标签的“h1”标签。

如何以编程方式删除它?

【问题讨论】:

  • 可能跑题了,但我必须警告你,由于这个 HTML 中的错误,当你在浏览器中查看时,表格不会在段落内。

标签: c# html regex ihtmlstring


【解决方案1】:

你可以使用HtmlAgilityPack:

var content = @"<h1>PDF Attachment</h1><h1 style=""color: rgb(51, 51, 51); text-align: center;""><p style=""font-size: 14px; font-weight: 400; text-align: justify;"">Your service detail are following</p><p style=""font-size: 14px; font-weight: 400; text-align: justify;""><table><tr><td></td></tr></table>&nbsp;<br></p><p style=""font-size: 14px; font-weight: 400; text-align: justify;""><br></p></h1>";

HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(content);
var h1NeedsToRemove = htmlDoc.DocumentNode.SelectNodes("/h1").Where(i => i.ChildNodes.Any(c => c.Name == "table")).FirstOrDefault();
var childNodesOfH1 = h1NeedsToRemove.ChildNodes;
h1NeedsToRemove.Remove();

htmlDoc.DocumentNode.AppendChildren(childNodesOfH1);

它会给你想要的输出:

<h1>PDF Attachment</h1>
<p style="font-size: 14px; font-weight: 400; text-align: justify;">Your service detail are following</p><p style="font-size: 14px; font-weight: 400; text-align: justify;">
    <table>
      <tr><td></td></tr>
    </table>&nbsp;
    <br>
 </p>
 <p style="font-size: 14px; font-weight: 400; text-align: justify;">  
   <br>
 </p>

【讨论】:

  • 但我需要这个输出

    PDF 附件

    您的服务详情正在关注

    表> 


  • 是的,它奏效了。谢谢 :) 只想再问一件事,我如何选择多个节点,如 h1 或 h2?
  • 你可以用ToList()代替FirstOrDefault()
  • 它自动删除了“p”的结束标签:(
  • 我想这样问“htmlDoc.DocumentNode.SelectNodes("/h1,/h2")"。我想要 h1 和 h2 节点。
猜你喜欢
  • 2011-05-24
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 2021-02-05
  • 2019-01-06
相关资源
最近更新 更多