从HTML中删除所有空/不必要的节点

Chr*_*son 3 c# html-agility-pack

删除所有空节点和不需要节点的首选方法是什么?例如

<p></p>应该删除,<font><p><span><br></span></p></font>也应该删除(因此在这种情况下br标签被认为是不必要的)

我是否必须使用某种递归函数?我正在思考这个问题:

 RemoveEmptyNodes(HtmlNode containerNode)
 {
     var nodes = containerNode.DescendantsAndSelf().ToList();

      if (nodes != null)
      {
          foreach (HtmlNode node in nodes)
          {
              if (node.InnerText == null || node.InnerText == "")
              {
                   RemoveEmptyNodes(node.ParentNode);
                   node.Remove();
               }
           }
       }
  }
Run Code Online (Sandbox Code Playgroud)

但这显然不起作用(stackoverflow异常).

use*_*979 12

不应删除的标记可以将名称添加到列表中,并且由于containerNode.Attributes.Count == 0(例如图像),也不会删除具有属性的节点

static List<string> _notToRemove;

static void Main(string[] args)
{
    _notToRemove = new List<string>();
    _notToRemove.Add("br");

    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml("<html><head></head><body><p>test</p><br><font><p><span></span></p></font></body></html>");
    RemoveEmptyNodes(doc.DocumentNode);
}

static void RemoveEmptyNodes(HtmlNode containerNode)
{
    if (containerNode.Attributes.Count == 0 && !_notToRemove.Contains(containerNode.Name) && string.IsNullOrEmpty(containerNode.InnerText))
    {
        containerNode.Remove();
    }
    else
    {
        for (int i = containerNode.ChildNodes.Count - 1; i >= 0; i-- )
        {
            RemoveEmptyNodes(containerNode.ChildNodes[i]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)