nam vo nam vo - 14 days ago 4
C# Question

How to remove duplicate br tag that exceeds a number of occurences?

I want to keep no more than 2

<br>
for each paragraph

string html = @"paragraph 1 a dkahdk ahkdhadk.<br><br><br>
<br>
paragraph 2 adshkad hkasdhkasdh.<br>
<br>
paragraph 3 akdash dkjahiewry iwery.<br>
<br><br>
paragraph 4 ljsdlfjsldfj.<br>
<br>
<br>
<br>";

HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();

doc.LoadHtml(html);
var xpath = "//text()[not(normalize-space())]";
var emptyNodes = doc.DocumentNode.SelectNodes(xpath);
foreach (HtmlNode emptyNode in emptyNodes)
{
emptyNode.Remove(); // remove \r\n
}
var nodes = doc.DocumentNode.SelectNodes("//br[following-sibling::br[3]]").ToList();
foreach (var node in nodes)
{
node.Remove();
}


The output is somehow it removes all
br
. The right output should be

paragraph 1 a dkahdk ahkdhadk.<br><br>
paragraph 2 adshkad hkasdhkasdh.<br><br>
paragraph 3 akdash dkjahiewry iwery.<br><br>
paragraph 4 ljsdlfjsldfj.<br><br>

Answer

A simple regex replace would suffice, as opposed to using HtmlAgilityPack. For example, using a multi-step process:

//use regex to find <br>, <br > or <br /> tags:
//var toNewLines = new Regex( @"<br\s?/?>" );
//var onlyNewLines = toNewLines.Replace(html, Environment.NewLine);
//or, since all br tags are <br>:
var onlyNewLines = html.Replace("<br>", Environment.NewLine);

var regex = new Regex( @"([" + Environment.NewLine + "\t])+" );

var result = regex.Replace(onlyNewLines, Environment.NewLine);

var finalResult = result.Replace(Environment.NewLine, "<br /><br />" + Environment.NewLine);
Comments