2013-02-20 162 views
0

我有一個表是這樣的:HTML敏捷包解析表

<table border="0" cellpadding="0" cellspacing="0" id="table2"> 
    <tr> 
     <th>Name 
     </th> 
     <th>Age 
     </th> 
    </tr> 
     <tr> 
     <td>Mario 
     </td> 
     <th>Age: 78 
     </td> 
    </tr> 
      <tr> 
     <td>Jane 
     </td> 
     <td>Age: 67 
     </td> 
    </tr> 
      <tr> 
     <td>James 
     </td> 
     <th>Age: 92 
     </td> 
    </tr> 
</table> 

,我使用的HTML敏捷包解析它。我曾嘗試這個代碼,但它沒有返回預期的結果:下面是代碼:

foreach (HtmlNode tr in doc.DocumentNode.SelectNodes("//table[@id='table2']//tr")) 
      { 
       //looping on each row, get col1 and col2 of each row 
       HtmlNodeCollection tds = tr.SelectNodes("td"); 
       for (int i = 0; i < tds.Count; i++) 
       { 
        Response.Write(tds[i].InnerText); 
       } 
      } 

我得到的每一列,因爲我想這樣做對某些內容的處理返回。

我在做什麼錯?

+0

你會得到什麼?什麼是錯誤?你得到了什麼? – 2013-02-20 19:20:24

+0

頁面只是保持循環,所以我假設一個無限循環。類型'System.OutOfMemoryException'的異常被拋出。 – mpora 2013-02-20 19:45:44

+0

http://stackoverflow.com/questions/14968729/html-agility-pack-loop-through-table-rows-and-columns/14990726#14990726 – mpora 2013-02-20 21:59:42

回答

1

你可以抓住從外foreach循環中的單元格內容:

foreach (HtmlNode td in doc.DocumentNode.SelectNodes("//table[@id='table2']//tr//td")) 
{ 
    Response.Write(td.InnerText); 
} 

而且我建議修剪和「去entitizing內部文本,以確保它是乾淨的:

Response.Write(HtmlEntity.DeEntitize(td.InnerText).Trim()) 

在你的源代碼中,[Age:78]和[Age:92]的單元在開始時有一個<th>標記,而不是<td>

0

這是我的解決方案。請注意你的HTML的格式不正確,因爲你有TH其中TD應該是:

<table border="0" cellpadding="0" cellspacing="0" id="table2"> 
    <tr> 
     <th>Name 
     </th> 
     <th>Age 
     </th> 
    </tr> 
     <tr> 
     <td>Mario 
     </td> 
     <td>Age: 78 
     </td> 
    </tr> 
      <tr> 
     <td>Jane 
     </td> 
     <td>Age: 67 
     </td> 
    </tr> 
      <tr> 
     <td>James 
     </td> 
     <td>Age: 92 
     </td> 
    </tr> 
</table> 

這是C#代碼:

using HtmlAgilityPack; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); 
      document.Load("page.html"); 

      List<HtmlNode> x = document.GetElementbyId("table2").Elements("tr").ToList(); 

      foreach (HtmlNode node in x) 
      { 
       List<HtmlNode> s = node.Elements("td").ToList(); 
       foreach (HtmlNode item in s) 
       { 
        Console.WriteLine("TD Value: " + item.InnerText); 
       } 
      } 
      Console.ReadLine(); 
     } 
    } 
} 

截圖: enter image description here

編輯:我必須補充說,如果您打算使用<th>標籤,則必須將它們包含在<thead>標籤內,然後將您的行放在<tbody>標籤內以便您的html格式良好:)

更多信息:http://www.w3schools.com/tags/tag_thead.asp

+0

我在回來之前解決了它。我現在正在應用正則表達式來提取年齡編號並創建一個名稱和年齡相同的csv文件(即:name,age)。 – mpora 2013-02-20 23:55:02

+0

祝你項目的人好運。 – 2013-02-20 23:55:42

+0

謝謝。 HTML敏捷包加速了我的進步。 – mpora 2013-02-21 00:36:22