1

我在这里得到了非常幽灵般的效果。我尝试替换一个 img 节点。如果我打印出文档 html 一次,什么都不会发生。如果我不打印出文档html,就可以成功替换img标签。真的很奇怪,谁能解释一下?在此处输入图像描述

我的html代码

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <div id="swap"></div>
</body>
</html>

和我的 C# 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.IO;
namespace htmlagile
{
    class Program
    {
        static void Main(string[] args)
        {
            HtmlDocument htmldoc = new HtmlDocument();
            string htmlstring;
            using (StreamReader sr = new StreamReader("HTMLPage1.html"))
            {
                htmlstring = sr.ReadToEnd();
            }
            htmldoc.LoadHtml(htmlstring);
            var div = htmldoc.DocumentNode.SelectNodes("//div");

            Console.WriteLine(htmldoc.DocumentNode.OuterHtml);

            foreach (var item in div)
            {
                HtmlNode newTag = htmldoc.CreateElement("p");
                newTag.SetAttributeValue("id", "change");
                item.ParentNode.ReplaceChild(newTag, item);
            }
            Console.WriteLine(htmldoc.DocumentNode.OuterHtml);
        }
    }
}

如果我注释掉我的第一个console.WriteLine,则可以成功更改元素。

在此处输入图像描述

4

1 回答 1

3

这是敏捷包中的一个错误。它们缓存 OuterHtml 和 InnerHtml 值。当发生更改时,它们只会使直接父级无效。因为您正在打印根目录,所以它仍然具有旧的缓存值。

http://htmlagilitypack.codeplex.com/workitem/30053

如果您更改为打印出父 div,您应该会看到实际执行了更改:

Console.WriteLine(div.OuterHtml);
于 2013-04-13T20:44:08.370 回答