问题
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>
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>
can someone guide me on how to use html agility pack to modify the existing html table and add more tags.
Thanks in advance.
回答1:
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;
}
来源:https://stackoverflow.com/questions/15870313/html-agility-pack-appending-thead-tbody-tfoot-in-existing-html-table