Skip to content Skip to sidebar Skip to footer

How Do I Remove Whitespace In HTML Source With Html Agility Pack And C#

Before posting I tried the solution from this thread: C# - Remove spaces in HTML source in between markups? Here is a snippet of the HTML I'm working with:

This is my text

Solution 1:

Remove the text nodes between the first and last paragraphs:

HTML:

var html = @"
<p>This is my text</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>This is next text</p>";

Parse it:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
var paragraphs = doc.DocumentNode.Descendants("p").ToList();
foreach (var item in paragraphs)
{
    if (item.InnerHtml == "&nbsp;") item.Remove();
}
var followingText = paragraphs[0]
    .SelectNodes(".//following-sibling::text()")
    .ToList();
foreach (var text in followingText) 
{
    text.Remove();
}

Result:

<p>This is my text</p><p>This is next text</p>

If you want to keep the line break between the paragraphs, use a for loop and call Remove() on all except the last text node.

for (int i = 0; i < followingText.Count - 1; ++i)
{
    followingText[i].Remove();
}

Result:

<p>This is my text</p>
<p>This is next text</p>

Post a Comment for "How Do I Remove Whitespace In HTML Source With Html Agility Pack And C#"