html敏捷包删除孩子

时间:2009-09-18 14:28:18

标签: c# html-agility-pack

我在尝试删除具有特定ID的div及其子代使用HTML Agility包时遇到了困难。我确信我只是错过了一个配置选项,但它周五而且我正在努力。

简化的HTML运行:

<html><head></head><body><div id='wrapper'><div id='functionBar'><div id='search'></div></div></div></body></html>

这是我所拥有的。敏捷包抛出的错误表明它找不到div结构:

<div id='functionBar'></div>

这是迄今为止的代码(取自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;
                }
            }
        }

3 个答案:

答案 0 :(得分:7)

  

bodyNode.RemoveChild(functionBarNode,FALSE);

但是functionBarNode不是bodyNode的子代。

functionBarNode.ParentNode.RemoveChild(functionBarNode, false)怎么样? (并忘记了关于查找bodyNode的内容。)

答案 1 :(得分:3)

您只需致电:

var documentNode = document.DocumentNode;
var functionBarNode = documentNode.SelectSingleNode("//div[@id='functionBar']");
functionBarNode.Remove();

它更简单,并且与:

相同
functionBarNode.ParentNode.RemoveChild(functionBarNode, false);

答案 2 :(得分:0)

这适用于多个:

HtmlDocument d = this.Download(string.Format(validatorUrl, Url));
foreach (var toGo in QuerySelectorAll(d.DocumentNode, "p[class=helpwanted]").ToList())
{
   toGo.Remove();
}
相关问题