0

実際、jquery を避けるために、テーブル リストに行を直接追加する予定です。

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());
      }
    }
  }
}
4

2 に答える 2

0

このコードは基本的に新しい行とセルを作成します。次に、セルにテキストを入力し、要素を親に追加します。

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);`
于 2013-02-10T04:15:07.000 に答える
0

やった、少し修正。それは私のために働いた。

    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); 
于 2013-02-10T12:50:05.760 に答える