Rvervuurt
Rvervuurt

Reputation: 8963

Use XSL to parse XML "color" attribute to fill a table cell

I'm learning XML and I'm running into the following problem: I have an attribute in my XML file which can have a color as content (e.g. <color>red</color>), but I don't know how to use it.

My XML:

<?xml version="1.0" encoding="UTF-8"?>
<cars>
    <car year="2002" manufacturer="Jet" model="Sardine Can 1.6L">
        <meter>95664</meter>
        <color>silver</color>
        <price>099900</price>
        <dealersecurity buyback="no"/>
    </car>
    <car year="2004" manufacturer="Jet" model="Sardine Can 2.0">
        <meter>81283</meter>
        <color>red</color>
        <price>129900</price>
        <dealersecurity buyback="no"/>
    </car>
    <car year="2007" manufacturer="Jet" model="Sardine Can 2.0">
        <meter>49741</meter>
        <color>black</color>
        <price>169999</price>
        <dealersecurity buyback="yes"/>
    </car>
</cars>

My XSL:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns="http://www.w3.org/1999/xhtml"
    version="1.0">
  <xsl:output method="xml"/>

  <xsl:template match="/cars">
    <html>
      <head><title>Second Hand Sardine Cans</title>  
        <link rel="stylesheet" type="text/css" href="style.css"/></head>
      <body>
      <h1>Second Hand Sardine Cans</h1>
      <table border="1"><th>Make</th><th>Model</th><th>Year</th><th>KMs</th><th>Color</th><th>Price</th><th>Warranty</th><xsl:apply-templates/></table>
      </body>
    </html>
  </xsl:template>

 <xsl:template match="cars/car">
  <tr><xsl:for-each select="cars/car"/>
  <td><xsl:value-of select="@manufacturer" /></td>
  <td><xsl:value-of select="@model" /></td>
  <td><xsl:value-of select="@year" /></td>
  <td><xsl:value-of select="meter" /></td>
        <xsl:apply-templates/></tr>
  </xsl:template>

  <xsl:template match="meter"/>

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

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

  </xsl:stylesheet>

What I have until now:
Result until now

But instead of it saying "Red" or "Black", I want that cell to fill with that exact color.

Thanks!

Edit: I fixed it with the help of Dimitre's answer. I added <td bgcolor="{color}"><xsl:value-of select="color" /></td> below <td><xsl:value-of select="meter" /></td>

Upvotes: 1

Views: 2559

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243479

Just change in your transformation:

   <tr>

to:

   <tr bgcolor="{color}">

Or, if you really want to have just one cell with that color, use in the template that matches color:

   <td bgcolor="{.}">

Upvotes: 2

Related Questions