2013-10-18 24 views
6

我正在嘗試在VS2008/.Net 3.5中使用HTMLAgilityPack。即使我將OptionUseIdAttribute設置爲true,我也會得到這個錯誤,儘管默認情況下它應該是true。HTMLAgilityPack - 您需要將UseIdAttribute屬性設置爲true以啓用此功能

Error Message: 
You need to set UseIdAttribute property to true to enable this feature 

Stack Trace: 
    at HtmlAgilityPack.HtmlDocument.GetElementbyId(String id) 

我試過版本1.4.6和1.4.0,都沒有工作。

1.4.6版 - Net20/HtmlAgilityPack.dll

版本1.4.0 - Net20/HtmlAgilityPack.dll

這是代碼,

HtmlWeb web = new HtmlWeb(); 
    HtmlDocument doc = web.Load(url); 
    HtmlNode table = doc.GetElementbyId("tblThreads"); 

這並沒有工作,要麼,

HtmlWeb web = new HtmlWeb(); 
    HtmlDocument doc = new HtmlDocument { OptionUseIdAttribute = true }; 
    doc = web.Load(url); 
    HtmlNode table = doc.GetElementbyId("tblThreads"); 

我該如何解決這個問題? 謝謝。

+0

如果你在加載你的'HtmlDocument'後放置了一個斷點,這個文檔是什麼樣的。即它是否正確加載? – Harrison

+0

是的,它看起來很好,在web.Load(url); – user471317

+0

你能指定url嗎? – Harrison

回答

3

首先我在1.4.0 HAP Dll上使用了ILSpy。我導航到的HTMLDocument類,並可以看到的getElementById方法是這樣的:

// HtmlAgilityPack.HtmlDocument 
/// <summary> 
/// Gets the HTML node with the specified 'id' attribute value. 
/// </summary> 
/// <param name="id">The attribute id to match. May not be null.</param> 
/// <returns>The HTML node with the matching id or null if not found.</returns> 
public HtmlNode GetElementbyId(string id) 
{ 
    if (id == null) 
    { 
     throw new ArgumentNullException("id"); 
    } 
    if (this._nodesid == null) 
    { 
     throw new Exception(HtmlDocument.HtmlExceptionUseIdAttributeFalse); 
    } 
    return this._nodesid[id.ToLower()] as HtmlNode; 
} 

後來我ILSpy分析「_nodesid」,因爲在你的情況下,由於某種原因,它沒有被設置。 「HtmlDocument.DetectEncoding(TextReader)」和「HtmlDocument.Load(TextReader)」將值分配給「_nodesid」。

因此,您可以嘗試一種替代方法來從URL中讀取內容,從而明確指定「_nodesid」值,例如

var doc = new HtmlDocument(); 
var request = (HttpWebRequest)WebRequest.Create(url); 
request.Method = "GET"; 
using (var response = (HttpWebResponse)request.GetResponse()) 
{ 
    using (var stream = response.GetResponseStream()) 
    { 
     doc.Load(stream); 
    } 
} 
var table = doc.GetElementbyId("tblThreads"); 

這種方法確保「HtmlDocument.Load(TextReader的)」之稱,並在代碼中,我可以看到_nodesid一定會得到分配,所以這種方式可以(我還沒有編譯的代碼我建議)工作。

+1

非常感謝。 – user471317

+0

沒問題。很高興我能幫上忙。 –

相關問題