2013-04-08 54 views
0

我一直在尋找谷歌,但沒有任何結果:(。我有一個HTML表像下面的Html敏捷包追加THEAD TBODY TFOOT在現有的HTML表格

<table> 
    <tr> 
     <td>column1</td> 
     <td>column2</td> 
    </tr> 
    <tr> 
     <td>column1rowtext</td> 
     <td>column2rowtext</td> 
    </tr> 
    <tr> 
     <td>column1rowtext</td> 
     <td>column2rowtext</td> 
    </tr> 
    <tr> 
     <td>column1EndText</td> 
     <td>column2EndText</td> 
    </tr> 
</table> 

我要添加THEAD,TBODY TFOOT和下面一樣使用的「HTML敏捷性包」

<table> 
    <thead> 
    <tr> 
     <td>column1</td> 
     <td>column2</td> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
    <td>column1rowtext</td> 
    <td>column2rowtext</td> 
    </tr> 
    <tr> 
    <td>column1rowtext</td> 
    <td>column2rowtext</td> 
    </tr> 
</tbody> 
<tfoot> 
    <tr> 
    <td>column1EndText</td> 
    <td>column2EndText</td> 
    </tr> 
</tfoot> 
</table> 

有人可以指導我如何使用HTML敏捷包修改現有的HTML表格,並添加更多標籤。

在此先感謝。

回答

1

Html Agility Pack構建了一個讀/寫DOM,因此您可以按照自己想要的方式重建它。這裏是一個示例代碼,似乎工作:

 HtmlDocument doc = new HtmlDocument(); 
     doc.Load("MyTest.htm"); 

     // get the first TR 
     CloneAsParentNode(doc.DocumentNode.SelectNodes("table/tr[1]"), "thead"); 

     // get all remaining TRs but the last 
     CloneAsParentNode(doc.DocumentNode.SelectNodes("table/tr[position()<last()]"), "tbody"); 

     // get the first TR (it's also the last, since it's the only one at that level) 
     CloneAsParentNode(doc.DocumentNode.SelectNodes("table/tr[1]"), "tfoot"); 


    static HtmlNode CloneAsParentNode(HtmlNodeCollection nodes, string name) 
    { 
     HtmlNode parent = nodes[0].ParentNode; 

     // create a new parent with the given name 
     HtmlNode newParent = nodes[0].OwnerDocument.CreateElement(name); 

     // insert before the first node in the selection 
     parent.InsertBefore(newParent, nodes[0]); 

     // clone all sub nodes 
     foreach (HtmlNode node in nodes) 
     { 
      HtmlNode clone = node.CloneNode(true); 
      newParent.AppendChild(clone); 
     } 

     // remove all sub nodes 
     foreach (HtmlNode node in nodes) 
     { 
      parent.RemoveChild(node); 
     } 
     return newParent; 
    } 
+0

非常感謝你這對我完美的作品:) – user2255930 2013-04-08 18:36:27