Would like to transform a price into a an expressed price range , so that I can say, for example, “Under $20” instead of $ 17.95. Using xml:choose is working for me, but when I try to put the result into a class attribute, I get an error:
Error during XSLT transformation: An unknown error has occurred ()
I’ve been reading up on xsl:variable but cannot seem to find the proper way to set the variable in this case.
The XML
<?xml version="1.0" encoding="UTF-8"?>
<productSearchResponse>
<status>SUCCESS</status>
<products found="20">
<product>
<itemNumber>50575</itemNumber>
<itemName>Example 1</itemName>
<price>$ 17.95</price>
</product>
...
<product>
<itemNumber>81588</itemNumber>
<itemName>Example 2</itemName>
<price>$ 25.95</price>
</product>
</products>
</productSearchResponse>
The stylesheet
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
</head>
<body>
<xsl:for-each select="/essentials/webservice">
<xsl:for-each select="document(@filename)/productSearchResponse/products/product">
<xsl:variable name="producingCountry" select="producingCountry"/>
<xsl:variable name="price" select="price"/>
<xsl:variable name="priceNoSymbol" select="translate($price,'$', '')"/>
<!-- Assign pricing bands -->
<xsl:choose>
<xsl:when test="$priceNoSymbol < '20'">
<xsl:variable name="priceBand" select="'under20'" />
</xsl:when>
<xsl:when test="$priceNoSymbol > '39.99'">
<xsl:variable name="priceBand" select="'20to40'" />
</xsl:when>
<xsl:otherwise>
<xsl:variable name="priceBand" select="'over40'" />
</xsl:otherwise>
</xsl:choose>
<!-- Make the product div -->
<div class="product {$producingCountry} {$price} {$priceNoSymbol} ">
<!-- How do I insert priceBand into the class attribute? ^ -->
<xsl:apply-templates select="itemName"/><br/>
<xsl:apply-templates select="producingCountry"/><br/>
<xsl:apply-templates select="price"/><br/><br/>
</div>
</xsl:for-each>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
The resulting html
<html>
<head>
<body>
<div class="product France $ 17.95 17.95 ">
Example 1
<br>
France
<br>
$ 17.95
<br>
<br>
</div>
...
<div class="product Portugal $ 25.95 25.95 ">
Example 2
<br>
Portugal
<br>
$ 25.95
<br>
<br>
</div>
</body>
</html>
Desired html
<html>
<head>
<body>
<div class="product France $ 17.95 17.95 under20 ">
Example 1
<br>
France
<br>
$ 17.95
<br>
<br>
</div>
...
<div class="product Portugal $ 25.95 25.95 20to40">
Example 2
<br>
Portugal
<br>
$ 25.95
<br>
<br>
</div>
</body>
</html>
I haven’t studied the entire question in detail, but you should replace
with
and
with
When you define a variable inside an
xsl:whenelement like that, it goes out of scope almost immediately and isn’t available outside thexsl:choose.