2011-12-17 43 views
3

我需要在XSLT中呈現以下格式。我有一個帶有5個元素(Text1,Text2 ... Text5)的<xsl:for-each循環,並且需要在每三個元素後包裝一個ul標籤。有什麼建議嗎?在XSLT中循環 - <xsl:for-each

<ul> 
    <li>Text1</li> 
    <li>Text2</li> 
    <li>Text3</li> 
</uL> 
<ul> 
    <li>Text4</li> 
    <li>Text5</li> 
</uL> 

回答

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>