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

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

应该删除

还应删除


(因此在这种情况下,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(); } } } } 

但这显然不起作用(stackoverflowexception)。

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

 static List _notToRemove; static void Main(string[] args) { _notToRemove = new List(); _notToRemove.Add("br"); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml("

test


"); 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]); } } }