user3618078
user3618078

Reputation: 55

Is there a way to conditionally sort in xslt?

I need to sort some content but only when an attribute is equal to CAT. I think I should be able to pass a property from my ant build file to the use-when attribute but it is not working. Any help would be appreciated

Here is the xslt that I have:

<xsl:for-each select="document(@fileRef)/foo/bar">
    <xsl:sort select="translate(child::Title/text(), '&gt;', '')" order="ascending" use-when="system-property('customerCode')='CAT'"
                          collation="http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive"/>
<!-- do some stuff here -->
</xsl:for-each>

Upvotes: 1

Views: 301

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167571

Using oXygen I got the following to work in an Ant file:

<xslt in="sample1.xml" out="sample1-transformed.xml" force="true" style="sheet1.xsl">
    <factory name="net.sf.saxon.TransformerFactoryImpl"/>
    <sysproperty key="cat" value="bar"/>
</xslt>

XML sample1.xml is e.g.

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <item>c</item>
    <item>a</item>
</root>

XSLT is

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">
    
    <xsl:mode on-no-match="shallow-copy"/>
    
    <xsl:output method="xml" indent="yes"/>
    
    <xsl:template match="/">
        <xsl:comment select="system-property('cat')"/>
        <xsl:next-match/>
    </xsl:template>
    
    <xsl:template match="root">
        <xsl:copy>
            <xsl:apply-templates select="item">
                <xsl:sort select="." use-when="system-property('cat') = 'foo'"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
    
</xsl:stylesheet>

and then the output items are sorted only if the Ant sets e.g. <sysproperty key="cat" value="foo"/>.

Upvotes: 1

Related Questions