BaconJuice
BaconJuice

Reputation: 3779

Setting an if condition with xml query in XSL

Hello guys was wondering if anyone could assist me with a logic implementation with XSL i'm having issues with.

I'm querying an xml file that returns 5 Microsoft Products and 2 Apple Products. What I want to do is display all the microsoft products depending how how many apple products were found.

So if only one apple product was found. Then it should grab 4 microsoft products but if 2 apple products were found it should grab 3 microsoft products to display.

my XSL so far

<xsl:call-template name="WRITEPRODUCTSET">
<xsl:with-param name="PRODUCTS" select="/Result/records[ @name = 'microsoft' ]" />
</xsl:call-template>
<xsl:call-template name="WRITEPRODUCTSET">
<xsl:with-param name="PRODUCTS" select="/Result/records[ @name != 'apple' ]" />
</xsl:call-template>

Thank you for reading and any help would be greatly appreciated!

Upvotes: 1

Views: 126

Answers (1)

helderdarocha
helderdarocha

Reputation: 23627

You can store your data in variables and then use them in calculations:

<xsl:variable name="apple-products"     select="//records[@name='apple']"/>
<xsl:variable name="microsoft-products" select="//records[@name='microsoft']"/>

For example:

<xsl:variable name="ms-products-to-return" 
       select="count($microsoft-products) - count($apple-products)"/> 

And then you can restrict the set with predicates to decide which of those products should be returned. For example, this stylesheet will return them in document order:

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

    <xsl:variable name="apple-products"     select="//records[@name='apple']"/>
    <xsl:variable name="microsoft-products" select="//records[@name='microsoft']"/>

    <xsl:template match="Result">
       <xsl:variable name="ms-products-to-return" 
           select="count($microsoft-products) - count($apple-products)"/> 
        <xsl:apply-templates 
             select="$microsoft-products[position() &lt;= $ms-products-to-return]" />
    </xsl:template>

    <xsl:template match="records">
        <xsl:copy-of select="."/>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions