1

我在尝试使用 HTML Agility 包删除具有特定 ID 的 div 及其子项时遇到困难。我确定我只是缺少一个配置选项,但它是星期五,我正在努力。

简化的 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;
                }
            }
        }
4

3 回答 3

7

bodyNode.RemoveChild(functionBarNode,false);

但是functionBarNode 不是bodyNode 的子节点。

怎么样functionBarNode.ParentNode.RemoveChild(functionBarNode, false)?(忘记寻找bodyNode的那一点。)

于 2009-09-18T15:04:03.170 回答
3

您可以简单地调用:

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

它更简单,并且与以下内容相同:

functionBarNode.ParentNode.RemoveChild(functionBarNode, false);
于 2012-07-09T12:31:50.107 回答
0

这将适用于多个:

HtmlDocument d = this.Download(string.Format(validatorUrl, Url));
foreach (var toGo in QuerySelectorAll(d.DocumentNode, "p[class=helpwanted]").ToList())
{
   toGo.Remove();
}
于 2013-03-11T13:01:42.223 回答