【问题标题】:Html Agility Pack appending thead tbody tfoot in existing html tableHtml Agility Pack 在现有的 html 表中附加 thead tbody tfoot
【发布时间】:2013-04-08 02:26:07
【问题描述】:

我一直在搜索谷歌但没有结果:(。我有一个如下所示的 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 表并添加更多标签。

提前致谢。

【问题讨论】:

    标签: html-agility-pack


    【解决方案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;
        }
    

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多