2011-09-19 35 views
0
<table class="result" summary="Summary Description."> 
<tbody> 
<tr> 
    <th scope="col" class="firstcol">Column 1</th> 
    <th scope="col">Column 2</th> 
    <th scope="col">Column 3</th> 
    <th scope="col" class="lastcol">Column 4</th> 
</tr> 
<tr class="even"> 
    <td class="firstcol">Text 1</td> 
    <td>Text 2</td> 
    <td>4Text 3</td> 
    <td class="lastcol">Text 4</td> 
</tr> 
</tbody></table> 

HTML Im感興趣的部分看起來像這樣。我想要文本1,文本2,文本3和文本4.使用HTMLAgilityPack,我如何提取數據?我谷歌和檢查這個網站,但沒有找到一些完全符合我的情況。使用HTMLAgilityPack提取特定的HTML文本

 if (htmlDoc.DocumentNode != null) 
     { 
      foreach (HtmlNode text in htmlDoc.DocumentNode.SelectNodes(???) 
      { 
       ??? 
      } 
     } 

回答

1

試試這個:

 var html = @"<table class=""result"" summary=""Summary Description.""> <tbody> <tr>  <th scope=""col"" class=""firstcol"">Column 1</th>  <th scope=""col"">Column 2</th>  <th scope=""col"">Column 3</th>  <th scope=""col"" class=""lastcol"">Column 4</th> </tr> <tr class=""even"">  <td class=""firstcol"">Text 1</td>  <td>Text 2</td>  <td>4Text 3</td>  <td class=""lastcol"">Text 4</td> </tr> </tbody></table>"; 
     var doc = new HtmlDocument(); 
     doc.LoadHtml(html); 
     var textNodes = doc.DocumentNode.SelectNodes(@"//tr[@class='even']/td/text()").ToList(); 
     foreach(var textNode in textNodes) 
     { 
      Console.WriteLine(textNode.InnerText); 
     } 
+0

工程就像一個夢!非常感謝你。 – mdc

+0

後續問題。如果還有一個叫做「奇怪」的類,並且我想擁有一個列表,就像它們在源代碼中一樣(偶數,奇數,偶數,奇數等)。那我怎麼寫這個問題呢?今天,我通過交換單詞「偶數」到「奇數」,將「奇數」保存到第二個列表中,然後將第二個列表添加到第一個列表中。但是他們會有錯誤的順序,因爲它將在開始時具有所有的「偶數」,並且最終將具有所有的「奇數」。 – mdc

+0

如果它們在我的問題中是動態的呢? http://stackoverflow.com/questions/24018750/how-to-use-htmlagilitypack-to-extract-html-data – SearchForKnowledge

相關問題