刪除所有空節點和不需要節點的首選方法是什麼?例如
應該刪除<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();
}
}
}
}
但這顯然不起作用(stackoverflow異常)。
不應刪除的標記可以將名稱添加到列表中,並且由於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]);
}
}
}