日期:2014-05-17  浏览次数:20447 次

c#如何将html的table数据转换为datatable
<table border="0" cellpadding="0" cellspacing="0" style="width: 143px" width="142">
<colgroup>
<col />
<col />
</colgroup>
<tbody>
<tr height="29">
<td height="29" style="width: 101px; height: 29px">
<strong>料號</strong></td>
<td style="width: 41px">
<strong>版序</strong></td>
</tr>
<tr height="25">
<td height="25" style="width: 101px; height: 25px">
A002A0092A</td>
<td style="width: 41px">
A</td>
</tr>
<tr height="25">
<td height="25" style="width: 101px; height: 25px">
A002A0092A</td>
<td style="width: 41px">
A</td>
</tr>
</tbody>
</table>


如例:上面的table内容是如下样式:

料號        版序
A002A0092A    A
A002A0092A    A

如何存成datatable或List?

------解决方案--------------------
正则获取strong,td中内容

Regex reg = new Regex(@"(?is)<strong[^>]*>(.*?)</strong>");
MatchCollection mc = reg.Matches(yourStr);
foreach (Match m in mc)
{
    TextBox1.Text += m.Groups[1].Value + "\n";
}
Regex reg = new Regex(@"(?is)<td\sheight=""25""[^>]*>(.*?)</td>");
------解决方案--------------------
用这个库:
http://www.codeplex.com/htmlagilitypack
 
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
 
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    Console.WriteLine("Found: " + table.Id);
    foreach (HtmlNode row in table.SelectNodes("tr")) {
        Console.WriteLine("row");
        foreach (HtmlNode cell in row.SelectNodes("th
------解决方案--------------------
td")) {
            Console.WriteLine("cell: " + cell.InnerText);
        }
    }