paquete de agilidad html eliminar niños
-
22-07-2019 - |
Pregunta
Tengo dificultades para tratar de eliminar un div con un ID en particular, y sus hijos usando el paquete HTML Agility. Estoy seguro de que solo me falta una opción de configuración, pero es viernes y estoy luchando.
Se ejecuta el HTML simplificado:
<html><head></head><body><div id='wrapper'><div id='functionBar'><div id='search'></div></div></div></body></html>
Esto es lo más lejos que tengo. El error arrojado por el paquete de agilidad muestra que no puede encontrar una estructura div:
<div id='functionBar'></div>
Aquí está el código hasta ahora (tomado de Stackoverflow ....)
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
// There are various options, set as needed
//htmlDoc.OptionFixNestedTags = true;
// filePath is a path to a file containing the html
htmlDoc.LoadHtml(Html);
string output = string.Empty;
// ParseErrors is an ArrayList containing any errors from the Load statement
if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count > 0)
{
// Handle any parse errors as required
}
else
{
if (htmlDoc.DocumentNode != null)
{
HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");
if (bodyNode != null)
{
HtmlAgilityPack.HtmlNode functionBarNode = bodyNode.SelectSingleNode ("//div[@id='functionBar']");
bodyNode.RemoveChild(functionBarNode,false);
output = bodyNode.InnerHtml;
}
}
}
Solución
bodyNode.RemoveChild (functionBarNode, false);
Pero functionBarNode no es hijo de bodyNode.
¿Qué tal functionBarNode.ParentNode.RemoveChild (functionBarNode, false)
? (Y olvídate de encontrar bodyNode).
Otros consejos
Simplemente puede llamar:
var documentNode = document.DocumentNode;
var functionBarNode = documentNode.SelectSingleNode("//div[@id='functionBar']");
functionBarNode.Remove();
Es mucho más simple y hace lo mismo que:
functionBarNode.ParentNode.RemoveChild(functionBarNode, false);
Esto funcionará para múltiples:
HtmlDocument d = this.Download(string.Format(validatorUrl, Url));
foreach (var toGo in QuerySelectorAll(d.DocumentNode, "p[class=helpwanted]").ToList())
{
toGo.Remove();
}