HTML Agility Pack在现有html表中附加了thead tbody [英] Html Agility Pack appending thead tbody tfoot in existing html table

查看:40
本文介绍了HTML Agility Pack在现有html表中附加了thead tbody的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索google,但没有结果:(.我有一个如下所示的HTML表格

I have been searching google but no result :(. i have a HTML table like below

<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>

我想使用"Html Agility Pack"(以下简称"Html Agility Pack")添加thead,tbody和tfoot,如下所示:

I want to add thead, tbody and tfoot like below using "Html Agility Pack"

<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表并添加更多标签.

can someone guide me on how to use html agility pack to modify the existing html table and add more tags.

谢谢.

推荐答案

Html Agility Pack构造了一个读/写DOM,因此您可以按自己的方式对其进行重建.这是一个似乎可行的示例代码:

The Html Agility Pack constructs a Read/Write DOM, so you can rebuild it the way you want. Here is a sample code that seems to work:

        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;
    }

这篇关于HTML Agility Pack在现有html表中附加了thead tbody的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆