html agilidade pacote de retirar as crianças
-
22-07-2019 - |
Pergunta
Eu estou tendo dificuldades para tentar remover um div com um determinado ID, e seus filhos usando o pacote HTML agilidade. Eu estou certo que eu estou faltando apenas uma opção de configuração, mas a sua sexta-feira e eu estou lutando.
Os simplificados corridas HTML:
<html><head></head><body><div id='wrapper'><div id='functionBar'><div id='search'></div></div></div></body></html>
Esta é tanto quanto eu tenho. O erro lançada por os shows agilidade pacote não é possível encontrar uma estrutura div:
<div id='functionBar'></div>
Aqui está o código até agora (retirado 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;
}
}
}
Solução
bodyNode.RemoveChild (functionBarNode, false);
Mas functionBarNode não é uma criança de bodyNode.
functionBarNode.ParentNode.RemoveChild(functionBarNode, false)
Que tal? (E esquecer o pouco sobre encontrar bodyNode.)
Outras dicas
Você pode simplesmente chamar:
var documentNode = document.DocumentNode;
var functionBarNode = documentNode.SelectSingleNode("//div[@id='functionBar']");
functionBarNode.Remove();
É muito mais simples, e faz o mesmo que:
functionBarNode.ParentNode.RemoveChild(functionBarNode, false);
Este trabalho vontade para múltiplos:
HtmlDocument d = this.Download(string.Format(validatorUrl, Url));
foreach (var toGo in QuerySelectorAll(d.DocumentNode, "p[class=helpwanted]").ToList())
{
toGo.Remove();
}