2013-04-22 127 views
0

我有下面的HTML下一个TR,添加TD元素到rowspan的TD

<!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> 

我已经currenty写这一段代码,通过该我可以得到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"); 
       } 
      } 
     } 
+1

我想从最后1小时..你能帮我吗 – 2013-04-22 12:46:33

+1

我已经编辑了我试过的代码的问题。 – 2013-04-22 12:54:59

回答

0

可能提示:对于条件,

cell.hasAttr("rowspan") 

获取行索引,如;

int index = row.getIndex(); 

然后通过索引+1得到下一行,就像;

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

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

+0

getIndex在Jsoup中不可用。 – 2013-04-25 09:11:25

0

您可以附加此行仅仅用这个代码:

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

for (Element row : rows) { 
    row.parent().nextElementSibling().append("<td>$50</td>"); 
} 
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以消除任何进一步的差异。

+0

看看我的解决方案,简单得多:) – MariuszS 2013-04-25 16:59:08