HTMLUNIT在HtmlTable的基础上添加行,编号为

问题描述:

实际上,为了避免jquery的东西,im计划直接在表中添加行。HTMLUNIT在HtmlTable的基础上添加行,编号为

你可以请帮助我通过在htmltable或其他方式(HTMLUNIT)中将值设置为字符串来动态添加行。

-------------- 
<table id="list4" class="scroll"> 
</table> 
------------------------ 

package com.test; 

import java.io.IOException; 
import java.net.MalformedURLException; 

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; 
import com.gargoylesoftware.htmlunit.WebClient; 
import com.gargoylesoftware.htmlunit.html.DomCharacterData; 
import com.gargoylesoftware.htmlunit.html.DomNode; 
import com.gargoylesoftware.htmlunit.html.HtmlPage; 
import com.gargoylesoftware.htmlunit.html.HtmlTable; 
import com.gargoylesoftware.htmlunit.html.HtmlTableCell; 
import com.gargoylesoftware.htmlunit.html.HtmlTableRow; 

public class TestMain { 

    public static void main(String args[]) 
     throws FailingHttpStatusCodeException, MalformedURLException, IOException { 
    final String htmlContent = "<html><head><title>foo</title></head><body><table id='table1'><tr id='row1'><td>cell1</td></tr><tr id='row2'><td>cell2</td></tr><tr id='row3'><td>cell3</td></tr><tr id='row4'><td>cell4</td></tr><tr id='row5'><td>cell5</td></tr><tr id='row6'><td>cell6</td></tr></table></body></html>"; 
    WebClient webClient = new WebClient(); 
    final HtmlPage page = loadPage(htmlContent); 
    final HtmlTable table = page.getHtmlElementById("list4"); 
    // want to add to the new row here 
    for (final HtmlTableRow row : table.getRows()) { 
     System.out.println("Found row"); 
     for (final HtmlTableCell cell : row.getCells()) { 
     System.out.println(" Found cell: " + cell.asText()); 
     } 
    } 
    } 
} 

我做了很少的修改。它为我工作。

final HtmlTable table = page.getHtmlElementById("highlight"); 

    HtmlTableRow newRow = (HtmlTableRow) page.createElement("tr"); 
    HtmlTableCell newCell = (HtmlTableCell) page.createElement("td"); 
    DomText cellContent = (DomText) page.createTextNode("Welcome Sireesh"); 

    newCell.appendChild((org.w3c.dom.Node) cellContent); 
    newRow.appendChild(newCell); 
    table.appendChild(newRow); 

此代码基本上是创建一个新的行和单元格。然后用一些文本填充单元格,然后将这些元素附加到他们的父母。

HtmlTableRow newRow = page.createElement("tr"); 
HtmlTableCell newCell = page.createElement("td"); 
Text cellContent = page.createTextNode("Hello World"); 
newCell.appendChild(cellContent); 
newRow.appendChild(newCell); 
table.appendChild(newRow); 
// you can also have `table.insertBefore(newRow, exisitingRow);`