我怎么能动态创建一个表?

时间:2014-12-22 03:54:37

标签: javascript xslt xml-parsing

我有这样的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 个答案:

答案 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