0

私は以下の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");
              }
          }
      }
4

3 に答える 3

0

考えられるヒント: 条件については、

cell.hasAttr("rowspan")

次のように行インデックスを取得します。

int index = row.getIndex();

次に、次の行をインデックス + 1 で取得します。

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

次に、この行に td-Element を追加します。これが、rowspan-row の次の行になります。

于 2013-04-22T13:39:09.320 に答える
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 属性も削除します。

于 2013-04-25T09:13:26.210 に答える