我正在尝试使用HtmlAgilityPack删除空的html节点。我想删除所有这样的节点:
<p><span> </span></p>
这是我正在尝试但它不起作用:
static string RemoveEmptyParagraphs(string html)
{
HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(html);
foreach (HtmlNode eachNode in document.DocumentNode.SelectNodes("//p/span/text() = ' '"))
eachNode.Remove();
html = document.DocumentNode.OuterHtml;
return html;
}
在使用document.LoadHtml(html);
加载html之前document.LoadHtml(html);
你可以这样做:
document.LoadHtml(html.Replace("<p><span> </span></p>", ""));
或者看看这个 :
static void RemoveEmptyNodes(HtmlNode containerNode)
{
if (containerNode.Attributes.Count == 0 && !_notToRemove.Contains(containerNode.Name) && (containerNode.InnerText == null || containerNode.InnerText == string.Empty) )
{
containerNode.Remove();
}
else
{
for (int i = containerNode.ChildNodes.Count - 1; i >= 0; i-- )
{
RemoveEmptyNodes(containerNode.ChildNodes[i]);
}
}
}