2013-04-13 41 views
1

我已經得到了真正ghosty效果在這裏。 我嘗試替換一個img節點。如果我將文檔html打印一次,則什麼都不會發生。 如果我不打印出文檔html,則可以成功替換img標籤。 這真的很奇怪,任何人都可以解釋嗎? enter image description hereGhosty HtmlAgilityPack

我的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,該元素可以成功地改變。

enter image description here

+0

缺乏詳細的信息來解決。快照不太清晰。 – David

+0

喜大衛 我附上完整的代碼。任何想法?? –

+0

沒有理由。你確定這是由於你的第一印嗎? – David

回答

3

這是敏捷包中的一個錯誤。他們緩存OuterHtml和InnerHtml值。發生變化時,他們只會使直接父母無效。由於您正在打印根目錄,它仍然具有舊的緩存值。

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

如果更改打印出父DIV,你應該看到的變化實際上進行:

Console.WriteLine(div.OuterHtml); 
+0

這是真的,但我能做些什麼呢? 是否有刷新緩存? –

+0

你可以嘗試修改根HTML節點,也可以編輯的靈活性包源來解決問題,問題做:http://htmlagilitypack.codeplex.com/workitem/30053 – LouD

+0

謝謝你,雖然,我決定用好老XmlDocument的 什麼htmlagilitypack的優勢,除了它是如此越野車? 它的大部分功能的XmlDocument都 –