将td元素添加到rowspan td的下一个tr

时间:2013-04-22 12:44:48

标签: java html jsoup

我的html以下,

<!DOCTYPE html>
<html>
<body>

<table border="1">
  <tr>
    <th>Month</th>
    <th>Savings</th>
    <th>Savings for holiday!</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
    <td rowspan="2">$50</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

</body>
</html>

我想使用jsoup生成以下html,

<tr>
    <th>Month</th>
    <th>Savings</th>
    <th>Savings for holiday!</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
    <td rowspan="2">$50</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
    <td>$50</td>
  </tr>

我当前写了这段代码,通过它我可以得到rowspan单元格及其相关的td索引

final Elements rows = table.select("tr");

      int rowspanCount=0;
      String rowspanString ="";
      for(Element row : rows){
          int rowspanIndex = 0;
          for(Element cell: row.select("td")){
              rowspanIndex++;
              if(cell.hasAttr("rowspan")){
                  rowspanCount = Integer.parseInt(cell.attr("rowspan"));

                  rowspanString = cell.ownText();

                  cell.removeAttr("rowspan");
              }
          }
      }

3 个答案:

答案 0 :(得分:0)

可能的提示:对于条件,

cell.hasAttr("rowspan")

获取行索引,例如;

int index = row.getIndex();

然后按索引+ 1获取下一行,如;

Element eRow = rows.get(index+1);

然后将td-Element附加到此行,这将是您对rowspan-row的下一行。

答案 1 :(得分:0)

您只需使用以下代码附加此行:

Elements rows = table.select("tr > td[rowspan=2]");

for (Element row : rows) {
    row.parent().nextElementSibling().append("<td>$50</td>");
}

答案 2 :(得分:0)

对所有内容进行编码后,我找到了解决方案。以下是代码,

for (Element row : rows) {
        int cellIndex = -1;
        if(row.select("td").hasAttr("rowspan")){
            for (Element cell : row.select("td")) {
                cellIndex++;
                if (cell.hasAttr("rowspan")) {
                    rowspanCount = Integer.parseInt(cell.attr("rowspan"));
                    cell.removeAttr("rowspan");

                    Element copyRow = row;

                    for (int i = rowspanCount; i > 1; i--) {
                        nextRow = copyRow.nextElementSibling();
                        Element cellCopy = cell.clone();
                        Element childTd = nextRow.child(cellIndex);
                        childTd.after(cellCopy);
                    }
                }
            }
        }
}

它将rowspan单元格复制到应包含它的所有以下行。同样删除属性rowspan以消除任何进一步的差异。