ThreadPeak
ThreadPeak

Reputation: 149

XSL for-each iteration

I have two for-each statements iterating and I want the output to be in vertical rather than horizontal format within the table.

Currently it outputs:

a b c
1 2 3

I want it to output:

a 1
b 2
c 3

Can someone help please? Here is the XSL:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="html" indent="no"/>
    <xsl:key name="names" match="Niche" use="."/>
    <xsl:key name="niche" match="row" use="Niche"/>

        <xsl:template match="/">
            <table border="1">

                <xsl:for-each select="//Niche[generate-id() = generate-id(key('names',.)[1])]">
                <xsl:sort select="."/>

                    <td>
                    <xsl:value-of select="."/>
                    </td>
                </xsl:for-each>

                <td><tr></tr></td>

                <xsl:for-each select="//row[generate-id(.)=generate-id(key('niche', Niche)[1])]">
                <xsl:sort select="Niche"/>

                    <td>
                    <xsl:value-of select="count(key('niche', Niche))"/>
                    </td>
                </xsl:for-each>

            </table>

    </xsl:template>
</xsl:stylesheet>

Sample XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="sample.xsl" ?>
<root>
    <row>
        <Niche>a</Niche>
    </row>
    <row>
        <Niche>b</Niche>
    </row>
    <row>
        <Niche>b</Niche>
    </row>
    <row>
        <Niche>c</Niche>
    </row>
    <row>
        <Niche>c</Niche>
    </row>
    <row>
        <Niche>c</Niche>
    </row>
</root>

Upvotes: 0

Views: 897

Answers (1)

JLRishe
JLRishe

Reputation: 101680

I'm pretty sure all you need to do is this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="no"/>
  <xsl:key name="niche" match="Niche" use="."/>

  <xsl:template match="/">
    <table border="1">

      <xsl:for-each select="//Niche[generate-id(.)=generate-id(key('niche', .)[1])]">
        <xsl:sort select="."/>
        <tr>
          <td>
            <xsl:value-of select="."/>
          </td>
          <td>
            <xsl:value-of select="count(key('niche', .))"/>
          </td>
        </tr>
      </xsl:for-each>

    </table>

  </xsl:template>
</xsl:stylesheet>

But please provide an example input XML so that we can verify.

On the sample input, this produces:

<table border="1">
  <tr>
    <td>a</td>
    <td>1</td>
  </tr>
  <tr>
    <td>b</td>
    <td>2</td>
  </tr>
  <tr>
    <td>c</td>
    <td>3</td>
  </tr>
</table>

To instead sort from highest to lowest occurrence count, you could replace this line:

<xsl:sort select="."/>

with this:

<xsl:sort select="count(key('niche', .))" order="descending" data-type="number"/>

Upvotes: 2

Related Questions