我有困难试图删除一个div与特定的ID,以及使用该HTML敏捷包其子女。我相信我只是缺少一个配置选项,但其周五和我挣扎。

在简化的HTML运行:

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

这是据我已经得到了。通过敏捷包引发的错误显示它不能找到一个div结构:

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

下面是到目前为止的代码(从#1采取....)

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;
                }
            }
        }
有帮助吗?

解决方案

  

bodyNode.RemoveChild(functionBarNode,FALSE);

但是functionBarNode不是bodyNode的子级。

如何functionBarNode.ParentNode.RemoveChild(functionBarNode, false)? (而忘记有关查找bodyNode位。)

其他提示

您可以简单地调用:

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

有更简单的,并进行了同样为:

functionBarNode.ParentNode.RemoveChild(functionBarNode, false);

这将用于多个工作:

HtmlDocument d = this.Download(string.Format(validatorUrl, Url));
foreach (var toGo in QuerySelectorAll(d.DocumentNode, "p[class=helpwanted]").ToList())
{
   toGo.Remove();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top