HTML敏捷包解析表

问题描述:

我有一个表是这样的: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

你可以抓住从外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>

这是我的解决方案。请注意你的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