2011-05-11 2 views
1

HtmlAgilityPack을 사용 중이며 td에서 title 클래스의 값을 선택하고 싶습니다. <a> 태그 안에 값 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 속성을 호출합니다. W3Schools에서

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

튜토리얼/자원 빠른 램프 업 꽤 좋다.

+0

를 제목의 끝에서, 당신은 아포스트로피 누락 또는 의도적입니까? –

0

XPath가 트릭을 수행해야합니다. 이 같은 뭔가 도움이 될 것입니다

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

이것은 나를 위해 일한 :

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