2014-12-22 52 views
0

我有这样的XML:如何动态创建表格?

<root> 
    <object a1="0" b1="2" c1="12/01" a2="0" b2="2" c2="12/03" a3="0" b3="2" c3="12/06"/> 
    <object a1="0" b1="2" c1="12/01" a2="0" b2="2" c2="12/03" /> 
    <object /> 
</root> 

我需要为每个对象表。

object[0]

---------------------------- 
a1 value | b1 value | c1 value| 
---------------------------- 
a2 value | b2 value | c2 value| 
---------------------------- 
a3 value | b3 value | c3 value| 
---------------------------- 

object[1]

---------------------------- 
a1 value | b1 value | c1 value| 
---------------------------- 
a2 value | b2 value | c2 value| 
---------------------------- 

但我不知道如何使用XSLT来做到这一点,因为循环每个属性都有不同的名称。 你能帮我解释一下吗? 我应该使用JavaScript解析属性吗?

预期HTML:

<table> 
<tr> 
    <td>a1 value</td> 
    <td>b1 value</td> 
    <td>c1 value</td> 
</tr> 
<tr> 
    <td>a2 value</td> 
    <td>b2 value</td> 
    <td>c2 value</td> 
</tr> 
<tr> 
    <td>a3 value</td> 
    <td>b3 value</td> 
    <td>c3 value</td> 
</tr> 
</table> 

的行数是依赖于对象的属性的数量。

+1

你能发布预期的输出HTML代码吗? –

+0

做属性都有相同的命名协议如图所示?即字母和增量行号 – charlietfl

+0

“*行数取决于对象中属性的数量。*”究竟如何? –

回答

0

下面是使用jQuery

var attrs = ['a', 'b', 'c']; 
var html = ''; 
$(xml).find('object').each(function (i) { 
    var ctr = 1, 
     $obj = $(this); 
    html += '<h3>Table #' + (i + 1) + '</h3><table>'; 

    do { 
     html += '<tr>'; 
     $.each(attrs, function (_, letter) {     
      html += '<td>' + $obj.attr(letter + ctr) + '</td>';    
     }); 
     ctr = $obj.attr('a' + (ctr + 1)) !== undefined ? ctr +1 : -1;   
     html += '</tr>'; 
    } while (ctr > 0); 
    html += '</table>'; 
}); 

$('body').append(html) 

这使得假设:如果第一属性a有一个行的值,所有其他属性也将存在该行

工作示例DEMO