2

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;
    }
2
  • Two things. First, if you want to delete any nodes, you can't use foreach but rather a backward for loop, because that is the only proper way to delete items from a list. Second, try changing the XPath string to "//p/span[text() = '&nbsp;']" or "//p/span[contains(text() = '&nbsp;')]" if you expect any spaces to appear in source HTML. Commented Mar 25, 2015 at 10:56
  • Thanks LightBulb, my xpath was a mess, that corrected the xpath. Commented Mar 25, 2015 at 15:20

1 Answer 1

2

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]);
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Assa. In the end, I used a simple html.Replace and that did the trick.
This code removed <p><img src="bytearray"/></p> which is wrong how to avoid this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.