XSLT how to output tags every 3rd iterat

2019-08-30 10:17发布

问题:

I have following XML and I am trying to group it into 3 <tag> into 1 <tr> element:

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

I want the following output:

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

I tried doing:

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

And the table must be within an existing <div> element.

回答1:

Try it this way?

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>


标签: xml xslt