view raw
nam vo nam vo - 6 months ago 33
C# Question

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

I want to keep no more than 2

for each paragraph

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

HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();

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)

The output is somehow it removes all
. 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>


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);