I’m working on an assignment where i am supposed to display grocery items in different ways. I can’t seem to figure if the xsl file is wrong or the xml file, or both.
Snippet of assignment:
Every
item in the inventory should have a sale price, regardless of whether or not it is on sale. An item that is on sale will be identified through a sale attribute with values “yes” or “no”. The sale attribute should be placed in the ID tag. If the sale tag is “yes” then the sale price is used, otherwise the regular price is used.
My problem is that only the regular prices will display regardless whether @sale=”yes” or “no”
<body>
<table>
<xsl:for-each select="catalog/item">
<tr>
<xsl:attribute name="sale">
<xsl:value-of select="id"/>
</xsl:attribute>
<td><xsl:value-of select="company"/></td>
<td><xsl:value-of select="product"/></td>
<td><xsl:value-of select="category"/></td>
<td><xsl:value-of select="description"/></td>
<xsl:choose>
<xsl:when test="@sale = 'yes'">
<td><xsl:value-of select="sale"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="price"/></td>
</xsl:otherwise>
</xsl:choose>
<td><xsl:value-of select="unit"/></td>
<td>
<img>
<xsl:attribute name="src">
<xsl:value-of select="picture"/>
</xsl:attribute>
</img>
</td>
</tr>
</xsl:for-each>
</table>
</body>
and the XML with sample of 2 items:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="sale.xsl" xsl:import href="company.xsl" xsl:import href="category.xsl"?>
<!DOCTYPE catalog SYSTEM "stock.dtd">
<catalog>
<item>
<id sale="yes">801</id>
<company>Grocery Gateway</company>
<product>Organic Strawberries</product>
<category>Produce</category>
<description>Fresh and organic strawberries imported from U.S.A. This product is subject to availability</description>
<price>5.99</price>
<sale>4.99</sale>
<unit>454g</unit>
<picture>pics/M6548[1].jpg</picture>
</item>
<item>
<id sale="no">101</id>
<company>Nestle </company>
<product>Pure Life Spring Water</product>
<category>Beverages</category>
<description>Ingredients are spring water, and ozone. </description>
<price>5.99</price>
<sale>4.99</sale>
<unit>24x500mL</unit>
<picture>pics/M58629[1].jpg</picture>
</item></catalog>
The reason why it’s not displaying the sale price properly is because you’re referencing the
@saleattribute incorrectly.The above tries to look for an attribute called
saleon the current for-each iteration (in this case beingcatalog/item, but the attribute doesn’t exist on this node in your XML). You’ll need to explicitly say that you’re looking for it on theidnode, like so :