XSLT如何每隔3次迭代输出标签

时间:2015-07-29 16:33:06

标签: xml xslt

我有以下XML,我正在尝试将其分为3 <tag>到1 <tr>元素:

<tags>
    <tag>
        <title>Title1</title>
        <img>src1</img>
        <text>text text text</text>
    </tag>
    <tag>
        <title>Title2</title>
        <img>src2</img>
        <text>text text text</text>
    </tag>
    <tag>
        <title>Title3</title>
        <img>src3</img>
        <text>text text text</text>
    </tag>
    <tag>
        <title>Title4</title>
        <img>src4</img>
        <text>text text text</text>
    </tag>
    ...
</tags>

我想要以下输出:

<tr>
    <td><h2>Title1</h2> <img src='src1'> <p>text text text</p></td>
    <td><h2>Title2</h2> <img src='src2'> <p>text text text</p></td>
    <td><h2>Title3</h2> <img src='src3'> <p>text text text</p></td>
</tr>
<tr>
    <td><h2>Title4</h2> <img src='src4'> <p>text text text</p></td>
    ...
</tr>
...

我尝试过:

<div class='some-class'>
    <table>
        <xsl:if test="position() mod 3 = 0">
            <tr>
        </xsl:if>

        <xsl:for-each select="/Tags/Tag" >
            <td>
                <h2><xsl:value-of select="title" /></h2>
                <img src="{src}" />
                <p><xsl:value-of select="text" /></p>
            </td>
        </xsl:for-each>

        <xsl:if test="position() mod 3 = 0">
            </tr>
        </xsl:if>
    </table>
</div>

该表必须位于现有的<div>元素内。

1 个答案:

答案 0 :(得分:2)

以这种方式试试吗?

XSLT 1.0

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

<xsl:template match="/tags">
    <div class='some-class'>
        <table border="1">
             <xsl:for-each select="tag[position() mod 3 = 1]">
                <tr>
                    <xsl:apply-templates select=". | following-sibling::tag[position() &lt; 3]"/>
                </tr>
            </xsl:for-each>
        </table>
    </div>
</xsl:template>

<xsl:template match="tag">
    <td>
        <h2>
            <xsl:value-of select="title" />
        </h2>
        <img src="{img}" />
        <p>
            <xsl:value-of select="text" />
        </p>
    </td>
</xsl:template>

</xsl:stylesheet>