I'm trying to remove span,font, b, s, strike (and other inner element) tags from HTML content while preserving text and <br>
tags inside it. For this purpose I'm using HTML agility pack. I managed to preserve text but <br>
tags are still a problem. Any ideas?
Here is the code:
private void removeTagsButPreserveText2(HtmlNode nodeToRemove)
{
var parent = nodeToRemove.ParentNode;
var prev = nodeToRemove.PreviousSibling;
if (prev != null)
{
var child = nodeToRemove.SelectNodes("./br");
if (child == null)
{
parent.InsertAfter(documentToSearch.CreateTextNode(nodeToRemove.InnerText + " "), prev);
nodeToRemove.Remove();
}
else
{
foreach (var item in child)
{
var parent2 = item.PreviousSibling;
if (parent2 != null)
{
if (parent2.InnerText.HasDate())
{
var newNode = parent.InsertAfter(documentToSearch.CreateTextNode(parent2.InnerText), prev);
parent.InsertAfter(documentToSearch.CreateElement("br"), newNode);
nodeToRemove.Remove();
}
}
}
}
}
}
For example, input will be:
<p><font face="Arial" size="2"><strike>
<span style="font-weight: 400"><font color="#000000">Paper
Submission (Full
Paper) Before
<span lang="en-us">September</span> 20, 201<span lang="en-us">2</span></font></span></strike><font color="#FF0000"><br>
Notification of
Acceptance On <span lang="en-us">October 5</span>, 201<span lang="en-us">2</span><br>
Authors'
Registration Before
<span lang="en-us">October 20</span>, 201<span lang="en-us">2</span><br>
ICNIT 2012 Conference
Dates November
17 - 18, 2012</font></font></p>
and the output should look like this:
<p>Paper Submission (Full Paper) Before September 20, 2012<br>
Notification of Acceptance On October 5, 2012<br>
Authors' Registration Before October 20, 2012<br>
ICNIT 2012 Conference
Dates November
17 - 18, 2012</p>
For this kind of HTML manipulation, there's a great library called the HTML Agility Pack.
Here's a similar question which will point to the right direction: Html Agility Pack - Remove element, but not innerHtml