2011-05-11 99 views
1

我正在使用HtmlAgilityPack,我希望從類別title的td中選擇值。我需要標籤中的值Battlefield 3如何選擇具有「foo」類的td?

我試過以下,只是爲了得到正確的td元素,並且我得到一個異常object is not set to an instance

var title = from item in document.DocumentNode.Descendants() 
      where item.Name == "td" && item.Attributes["class"].Value == "title" 
      select item.InnerHtml; 

有了這個小例子,我可能會弄清楚我需要的其餘部分。

謝謝你的建議。

<tr class="first-in-year"> 
    <td class="year">2011</td> 

    <td class="img"><a href="/battlefield-3/61-27006/"><img src= 
    "http://media.giantbomb.com/uploads/6/63038/1700748-bf3_thumb.jpg" alt=""></a></td> 

    <td class="title"> 
    <a href="/battlefield-3/61-27006/">Battlefield 3</a> 

    <p class="deck">Battlefield 3 is DICE's next installment in the franchise and 
    will be on PC, PS3 and Xbox 360. The game will feature jets, prone, a 
    single-player and co-op campaign, and 64-player multiplayer (on PC). It's due out 
    in Fall of 2011.</p> 
    </td> 
</tr> 

回答

4

嘗試使用帶有類或其他屬性說明符的XPath選擇器。

//td[@class='title']/a 

它應該爲您提供具有「標題」類的元素中的所有元素。然後,您將遍歷該NodeCollection並調用node.InnerText屬性。

var nodes = doc.DocumentNode.SelectNodes("//td[@class='title']/a"); 
    foreach(HtmlNode node in nodes) 
    { 
    string title = node.InnerText; 
    } 

W3Schools的教程/資源對於快速啓動非常有用。

+0

在節目的結束,是否缺少撇號或者是故意的嗎? – 2011-05-11 22:00:58

0

XPath應該訣竅。像這樣的東西應該有所幫助:

var text = document.DocumentNode.SelectNodes("//td[@class='title']/a"); 
0

這爲我工作:

string title = doc.DocumentNode.SelectSingleNode(@"//td[@class='title']/a").InnerText;