在XSLT 1.0中使用数组来构建具有不均匀行数的表

时间:2014-11-07 21:39:56

标签: html arrays xslt

我有一个XML结构,如下所示:

<people>
    <attending>
        <person><firstname>John</firstname><lastname>Doe</lastname></person>
        <person><firstname>George</firstname><lastname>Washington</lastname></person>
        <person><firstname>Henry</firstname><lastname>Dodson</lastname></person>
    </attending>
    <maybe>
        <person><firstname>Jackie</firstname><lastname>Gleason</lastname></person>
        <person><firstname>Jill</firstname><lastname>Hill</lastname></person>
    </maybe>
</people>

我想使用XSLT 1.0构建一个HTML表,其中包含attendingmaybe元素中的信息,但它们永远不会保证具有相同数量的元素。我希望桌子看起来像这样(或类似的):

<table>
    <tr>
        <th>Attending</th><th>Maybe</th>
    </tr>
    <tr>
        <td>John Doe</td><td>Jackie Gleason</td>
    </tr>
    <tr>
        <td>George Washington</td><td>Jill Hill</td>
    </tr>
    <tr>
        <td>Henry Dodson</td><td>&nbsp;</td>
    </tr>
</table>

因为我一次只能在一个元素上执行xsl:for-each,所以我可以构建两个单独的表(一次一列),并将每个表并排放在两个单元格中更大,更包围的桌子。但是,我需要一个表。 (如果您想知道原因,那就是跨浏览器样式的原因,并且表格中的表格难以跨浏览器控制。一个表格可以减轻很多这一点。)

下一个显而易见的事情是构建两个数组,一个使用attending节点集,一个使用maybe节点集,然后执行基于xsl:for-each的索引。查找每个数组中的索引,因为HTML表当然需要一次构建一行,但不幸的是我的数据存储为列。此外,XSLT事先并不知道每个attendingmaybe会有多少,因此它必须能够动态处理它。

  • XSLT 1.0是否支持此类阵列?
  • 如何对此类数组进行xsl:for-each次迭代? (与$attending[index]中的index是我的&#34;每个&#34;计数器一样)

我更喜欢XSLT 1.0的答案,因为这是我受限制的框架,但我很乐意听到如何在XSLT的更高版本中完成这项工作。

1 个答案:

答案 0 :(得分:2)

这是你可以看到它的一种方式:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="/people">
    <table>
        <tr>
            <th>Attending</th>
            <th>Maybe</th>
        </tr>       
        <xsl:call-template name="rows"/>
    </table>
</xsl:template>

<xsl:template name="rows">
    <xsl:param name="i" select="1"/>
    <xsl:if test="*/person[$i]">
        <tr>
            <td>
                <xsl:apply-templates select="attending/person[$i]"/>
            </td>
            <td>
                <xsl:apply-templates select="maybe/person[$i]"/>
            </td>
        </tr>
        <xsl:call-template name="rows">
            <xsl:with-param name="i" select="$i + 1"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

<xsl:template match="person">
    <xsl:value-of select="firstname"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="lastname"/>
</xsl:template>

</xsl:stylesheet>