xsl-list
[Top] [All Lists]

Re: group by number

2003-11-28 07:38:47
Andreas Lindahl wrote:

Hi

I have an xml file which looks pretty much like this:

<snip/>

Each group node should contain three item nodes.

How should I do this with XSLT?

use the position function...
I set the root node to result


<xsl:template match="/">
<result>
  <xsl:apply-templates select="//item" mode="test"/>
</result>
</xsl:template>

<xsl:template match="item" mode="test">
  <xsl:if test="position() mod 3 = 1">
    <group id="{ceiling(position() div 3)}">
      <xsl:apply-templates select="."/>
      <xsl:apply-templates select="following-sibling::item[1]"/>
      <xsl:apply-templates select="following-sibling::item[2]"/>
   </group>
  </xsl:if>
</xsl:template>


<xsl:template match="item">
  <xsl:copy><xsl:apply-templates select="*|@*|text()"/></xsl:copy>
</xsl:template>

----

java org.apache.xalan.xslt.Process -IN items.xml -XSL items.xsl
<?xml version="1.0" encoding="UTF-8"?>
<result>
<group id="1">
<item>1</item>
<item>2</item>
<item>3</item>
</group>
<group id="2">
<item>4</item>
<item>5</item>
<item>6</item>
</group>
<group id="3">
<item>7</item>
<item>8</item>
<item>9</item>
</group>
</result>


HTH

cheers

-- 

XPath free testing software :  http://lantern.sourceforge.net
Frédéric Laurent                     http://www.opikanoba.org

 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list



<Prev in Thread] Current Thread [Next in Thread>