Xml 如何获取XSLT中的每两个元素

Xml 如何获取XSLT中的每两个元素,xml,xslt,foreach,Xml,Xslt,Foreach,我有这样的XML: <image> <image url="img1.jpg" /> <image url="img2.jpg" /> <image url="img3.jpg" /> <image url="img4.jpg" /> <image url="img5.jpg" /> </image> 我需要这样制作HTML: <image> <image url=

我有这样的XML:

<image>
  <image url="img1.jpg" />
  <image url="img2.jpg" />
  <image url="img3.jpg" />
  <image url="img4.jpg" />
  <image url="img5.jpg" />
</image>

我需要这样制作HTML:

<image>
  <image url="img1.jpg" />
  <image url="img2.jpg" />
  <image url="img3.jpg" />
  <image url="img4.jpg" />
  <image url="img5.jpg" />
</image>
试着这样做:

XSLT1.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="/image">
    <ul>
        <xsl:for-each select="image[position() mod 2 = 1]">
            <li>
                <xsl:apply-templates select=". | following-sibling::image[1]" />
            </li>
        </xsl:for-each>
    </ul>
</xsl:template>

<xsl:template match="image">
    <img src="{@url}" />
</xsl:template>

</xsl:stylesheet>


在XSLT 2.0中,您可以执行以下操作:

<xsl:template match="/image">
    <ul>
        <xsl:for-each-group select="image" group-starting-with="image[position() mod 2 = 1]">
            <li>
                <xsl:apply-templates select="current-group()" />
            </li>
        </xsl:for-each-group>
    </ul>
</xsl:template>

<xsl:template match="image">
    <img src="{@url}" />
</xsl:template>