在XSLT中循环 - <xsl:for-each>

3

我需要在XSLT中呈现以下格式。我有一个<xsl:for-each循环,其中包含5个元素(Text1、Text2…Text5),需要在每三个元素之后包装一个ul标签。请问有什么建议?

<ul>
    <li>Text1</li>
    <li>Text2</li>
    <li>Text3</li>
</uL>
<ul>
    <li>Text4</li>
    <li>Text5</li>
</uL>
2个回答

4

很好的问题,+1。

这种转换

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="thing[position() mod 3 = 1]">
  <ul>
   <xsl:apply-templates mode="inGrpoup" select=
    ".|following-sibling::*[not(position() > 2)]"/>
  </ul>
 </xsl:template>

 <xsl:template match="thing" mode="inGrpoup">
  <li><xsl:value-of select="."/></li>
 </xsl:template>
 <xsl:template match="text()"/>
</xsl:stylesheet>

当应用于以下XML文档时:

<things>
    <thing>1</thing>
    <thing>2</thing>
    <thing>3</thing>
    <thing>4</thing>
    <thing>5</thing>
    <thing>6</thing>
    <thing>7</thing>
    <thing>8</thing>
</things>

产生所需的、正确的结果(将物品分组为连续的三个):

<ul>
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
<ul>
   <li>4</li>
   <li>5</li>
   <li>6</li>
</ul>
<ul>
   <li>7</li>
   <li>8</li>
</ul>

解释:

  1. 匹配模板模式,匹配三个thing元素中的第一个thing

  2. 使用模式来处理一组thing元素(不同于初始启动thing的处理方式),一旦确定。


2
一个有趣的问题。我在下面概述了一种解决方案,它使用<xsl:key>来识别每个三元组,并使用一些模运算。
输入文档:
<TestDocument>
    <Element>Alpha</Element>
    <Element>Bravo</Element>
    <Element>Charlie</Element>
    <Element>Delta</Element>
    <Element>Echo</Element>
    <Element>Foxtrot</Element>
    <Element>Golf</Element>
    <Element>Hotel</Element>
</TestDocument>

样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>

    <!-- Declare a key to identify each group of 3 elements -->
    <xsl:key name="positionKey" match="/TestDocument/Element" use="floor((position() - 2) div 3)"/>
    <xsl:template match="/TestDocument">
        <html>
            <!-- Iterate over the first element in each group -->
            <xsl:for-each select="Element[(position() - 1) mod 3 = 0]">
                <ul>
                    <!-- Grab all elements from this group -->
                    <xsl:apply-templates select="key('positionKey', position()-1)"/>
                </ul>
            </xsl:for-each>
        </html>
    </xsl:template>

    <xsl:template match="Element">
        <li><xsl:value-of select="."/></li>
    </xsl:template>
</xsl:stylesheet>

结果:

<html>
    <ul>
        <li>Alpha</li>
        <li>Bravo</li>
        <li>Charlie</li>
    </ul>
    <ul>
        <li>Delta</li>
        <li>Echo</li>
        <li>Foxtrot</li>
    </ul>
    <ul>
        <li>Golf</li>
        <li>Hotel</li>
    </ul>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接