Ho visto alcune domande correlate qui, ma non parlano esattamente dello stesso problema che sto affrontando.
Voglio utilizzare l' HTML Agility Pack per rimuovere i tag indesiderati dal mio codice HTML senza perdere il contenuto all'interno dei tag.
Quindi, ad esempio, nel mio scenario, vorrei conservare i tag " b
", " i
" e " u
".
E per un input come:
<p>my paragraph <div>and my <b>div</b></div> are <i>italic</i> and <b>bold</b></p>
L'HTML risultante dovrebbe essere:
my paragraph and my <b>div</b> are <i>italic</i> and <b>bold</b>
Ho provato ad usare il metodo di Remove
HtmlNode
, ma rimuove anche il mio contenuto. Eventuali suggerimenti?
Ho scritto un algoritmo basato sui suggerimenti di Oded. Ecco qui. Funziona come un fascino.
Rimuove tutti i tag tranne i nodi strong
, em
, u
e di testo non elaborati.
internal static string RemoveUnwantedTags(string data)
{
if(string.IsNullOrEmpty(data)) return string.Empty;
var document = new HtmlDocument();
document.LoadHtml(data);
var acceptableTags = new String[] { "strong", "em", "u"};
var nodes = new Queue<HtmlNode>(document.DocumentNode.SelectNodes("./*|./text()"));
while(nodes.Count > 0)
{
var node = nodes.Dequeue();
var parentNode = node.ParentNode;
if(!acceptableTags.Contains(node.Name) && node.Name != "#text")
{
var childNodes = node.SelectNodes("./*|./text()");
if (childNodes != null)
{
foreach (var child in childNodes)
{
nodes.Enqueue(child);
parentNode.InsertBefore(child, node);
}
}
parentNode.RemoveChild(node);
}
}
return document.DocumentNode.InnerHtml;
}
Ho risposto a @mathias e ho migliorato il suo metodo di estensione in modo da poter fornire un elenco di tag da escludere come List<string>
(ad esempio {"a","p","hr"}
). Ho anche corretto la logica in modo che funzioni correttamente in modo ricorsivo:
public static string RemoveUnwantedHtmlTags(this string html, List<string> unwantedTags)
{
if (String.IsNullOrEmpty(html))
{
return html;
}
var document = new HtmlDocument();
document.LoadHtml(html);
HtmlNodeCollection tryGetNodes = document.DocumentNode.SelectNodes("./*|./text()");
if (tryGetNodes == null || !tryGetNodes.Any())
{
return html;
}
var nodes = new Queue<HtmlNode>(tryGetNodes);
while (nodes.Count > 0)
{
var node = nodes.Dequeue();
var parentNode = node.ParentNode;
var childNodes = node.SelectNodes("./*|./text()");
if (childNodes != null)
{
foreach (var child in childNodes)
{
nodes.Enqueue(child);
}
}
if (unwantedTags.Any(tag => tag == node.Name))
{
if (childNodes != null)
{
foreach (var child in childNodes)
{
parentNode.InsertBefore(child, node);
}
}
parentNode.RemoveChild(node);
}
}
return document.DocumentNode.InnerHtml;
}