bearaman
bearaman

Reputation: 1091

How to remove empty html nodes with HtmlAgilityPack?

I'm trying to remove empty html nodes with HtmlAgilityPack. I want to remove all nodes like this:

<p><span>&nbsp;</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() = '&nbsp;'"))
            eachNode.Remove();
        html = document.DocumentNode.OuterHtml;
        return html;
    }

Upvotes: 2

Views: 4337

Answers (1)

Sid
Sid

Reputation: 14896

Before loading the html with document.LoadHtml(html); you can do this:

document.LoadHtml(html.Replace("<p><span>&nbsp;</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

Related Questions