HtmlAgilityPack无法替换子元素,为什么?

3
我添加了一个功能来请求“http://cnblogs.com”页面。当我使用HtmlAgilityPack替换更多的HtmlNode时,会遇到一些混淆的问题——无法替换。 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;//I Use NuGet to include HtmlAgilityPack(Vs2012)

namespace CatchWebSample
{
    class Program
    {
        public static void Main(string[] args)
        {
            HtmlDocument document = new HtmlDocument();
            WebClient wc = new WebClient();
            wc.Encoding = Encoding.GetEncoding("utf-8");
            string content = wc.DownloadString("http://cnblogs.com");
            document.LoadHtml(content);
            string oldContent = document.DocumentNode.OuterHtml;

            //here, I want to replace all xpath= //div[@class='post_item_foot'] htmlnodes
            HtmlNodeCollection targetNodeCollection = document.DocumentNode.SelectNodes(@"//div[@class='post_item_foot']");

            HtmlNode newHtmlNode;
            if (targetNodeCollection != null && targetNodeCollection.Count > 0)
            {
                for (int i = 0; i < targetNodeCollection.Count; i++)
                {
                    var targetNode = targetNodeCollection[i];
                    newHtmlNode = document.CreateElement("span");
                    newHtmlNode.InnerHtml = HtmlDocument.HtmlEncode("###### REPLACED CONTENT #########");

                    targetNode.ParentNode.ReplaceChild(newHtmlNode, targetNode);
                }

                content = document.DocumentNode.OuterHtml;

                //but the result is same of the original data,why it can not replace ?
                bool flag = string.Compare(oldContent, content) == 0;
            }

        }
    }
}

我很困惑,为什么呢?



我修改了你发布的代码示例,这是它应该看起来的样子吗? - jessehouwing
你的HtmlAgilityPack版本低于4.5吗? - Kuzgun
对我来说它正常工作。确保你正在运行最新版本。 - Simon Mourier
@Kuzgun 我使用 NuGet 来包含这个 dll,我检查了一下——版本是 v4.0.30319,这是问题所在吗? - tiancaolin
@Simon Mourier,请问您能告诉我最新版本在哪里下载吗? - tiancaolin
显示剩余12条评论
1个回答

2

replaceChild()和insertAfter()突然都对我失效了。

我的最佳替代方案是用“新的html字符串”替换innerhtml。

targetnode.innerhtml = newNodeAsString;

编辑:

HtmlAgilityPack存在插入值/节点时的一个 bug,由于一些缓存使其更快运行。

这就是为什么我弃用它并使用 AngleSharp 的原因。

编辑:

在2017年中期,HAP正在这里开发。我不会回头使用它。此外,你不能在 HAP 上创建问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接