Reputation: 1091
I'm trying to remove empty html nodes with HtmlAgilityPack. I want to remove all nodes like this:
<p><span> </span></p>
Here's what I'm trying but it's not working:
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;
}
Upvotes: 2
Views: 4337
Reputation: 14896
Before loading the html with document.LoadHtml(html);
you can do this:
document.LoadHtml(html.Replace("<p><span> </span></p>", ""));
Or have a look at this:
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]);
}
}
}
Upvotes: 2