Dites que je veux supprimer la balise span de ce code HTML:
<html><span>we do like <b>bold</b> stuff</span></html>
Je m'attends à ce morceau de code pour faire ce que je suis après
string html = "<html><span>we do like <b>bold</b> stuff</span></html>";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode span = doc.DocumentNode.Descendants("span").First();
span.ParentNode.RemoveChild(span, true); //second parameter is 'keepGrandChildren'
Mais la sortie ressemble à ceci:
<html> stuff<b>bold</b>we do like </html>
Il semble que les nœuds enfants soient inversés au cours de la période. Est-ce que je fais quelque chose de mal?
Ressemble à un bogue dans HtmlAgilityPack - voir leur registre de problèmes:
http://htmlagilitypack.codeplex.com/workitem/9113
Fait intéressant, cela a été soulevé il y a 4 ans ...
Voici un extrait qui supprimera toutes les balises span (ou toute autre balise que vous spécifiez) et maintiendra les autres nœuds dans le bon ordre.
void Main()
{
string html = "<html><span>we do like <b>bold</b> stuff</span></html>";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
RemoveTags(doc, "span");
Console.WriteLine(doc.DocumentNode.OuterHtml);
}
public static void RemoveTags(HtmlDocument html, string tagName)
{
var tags = html.DocumentNode.SelectNodes("//" + tagName);
if (tags!=null)
{
foreach (var tag in tags)
{
if (!tag.HasChildNodes)
{
tag.ParentNode.RemoveChild(tag);
continue;
}
for (var i = tag.ChildNodes.Count - 1; i >= 0; i--)
{
var child = tag.ChildNodes[i];
tag.ParentNode.InsertAfter(child, tag);
}
tag.ParentNode.RemoveChild(tag);
}
}
}
foreach (HtmlNode child in tag.ChildNodes)
{
tag.ParentNode.InsertBefore(child, tag);
}
tag.Remove();