0

我一直在搜索谷歌但没有结果:(。我有一个如下所示的 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>

我想像下面一样使用“Html Agility Pack”添加thead、tbody和tfoot

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

提前致谢。

4

1 回答 1

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;
    }
于 2013-04-08T06:27:42.260 回答