Vito
Vito

Reputation: 776

XSL sort and each

I have these two files:

XML

<?xml version="1.0" encoding="UTF-8"?>

<Store>
    <Plant id="10">
        <Common>Pianta carnivora</Common>
        <Botanical>Dionaea muscipula</Botanical>
        <Quantity>10</Quantity>  
    </Plant>
    <Flower id="3">
        <Common>Fiore di prova</Common>
        <Quantity>999</Quantity>
    </Flower>
    <Plant id="20">
        <Common>Canapa</Common>
        <Botanical>Cannabis</Botanical>
        <Quantity>2</Quantity>  
    </Plant>    

    <Plant id="30">
        <Common>Loto</Common>
        <Botanical>Nelumbo Adans</Botanical>
        <Quantity>3</Quantity>  
    </Plant>    

</Store>

XSL

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

    <xsl:template match="/">
        <html>
            <xsl:apply-templates/>
        </html>
    </xsl:template>

    <xsl:template match="Store">
        <body>
            <xsl:for-each select="Plant">
                <p>
<xsl:sort select="Quantity"/>   
<xsl:value-of select="Quantity"/>

                </p>
            </xsl:for-each>
        </body>
    </xsl:template>


</xsl:stylesheet>

The XSL doesn't sort. I don t have any kind of output. I really don't know how it doesn't work. The code seems correct. If you take off the sort tag , you will see the output. Within the sort, you will not see anything.

Upvotes: 3

Views: 138

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52858

You need to move your xsl:sort to be the first child of xsl:for-each. It's not valid where it is now.

You might also want to change your data-type to number.

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

    <xsl:template match="/">
        <html>
            <xsl:apply-templates/>
        </html>
    </xsl:template>

    <xsl:template match="Store">
        <body>
            <xsl:for-each select="Plant">
                <xsl:sort select="Quantity" data-type="number"/>
                <p>
                    <xsl:value-of select="Quantity"/>
                </p>
            </xsl:for-each>
        </body>
    </xsl:template>

</xsl:stylesheet>

You could do the same type of thing with xsl:apply-templates too...

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

    <xsl:template match="/Store">
        <html>
            <body>
                <xsl:apply-templates select="Plant/Quantity">
                    <xsl:sort data-type="number"/>
                </xsl:apply-templates>
            </body>
        </html>
    </xsl:template>

    <xsl:template match="Quantity">
        <p><xsl:value-of select="."/></p>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions